Utilizing the fetch() method in Vuex to obtain a restful API

Struggling to integrate my API data through Vuex, I am in dire need of a reliable guide or perhaps someone who can assist me with this task. Previously, without using Vuex, all my requests functioned flawlessly. However, now I'm unsure about the necessary steps. Here's a glimpse of my code:

data() {
    return {
      testArray: []
    }; 
 methods: {

    getJsonData() {
      fetch(
        "https://app.ticketmaster.com/discovery/v2/events.json?countryCode=" +
          this.countriesDrop +
          "&apikey=xxxxxxxxxxxxxxxxxxxxxxxx",
        {
          method: "GET"
        }
      )
        .then(response => {
          return response.json();
        })
        .then(test => {console.log(this.testArray)
          this.testArray = test._embedded.events;
        })
        .catch(err => {
          console.log(err);
        });
    },
    watch: {
    countriesDrop: function(val) {
         this.getJsonData();
    }
  },

The request also includes an external element that adjusts according to the watcher and user-assigned values. I have successfully set up Vuex and other plugins...I just lack the know-how to proceed. Any precise tutorials, links, or detailed assistance on resolving this basic issue would be greatly appreciated. Thank you!

Answer №1

Your code currently does not involve the use of Vuex. It seems like you intend to update the state in such a way that the getJsonData() method is triggered based on the contents of the store.

Here's an example snippet demonstrating how asynchronous operations are handled in a Vuex scenario.

const store = new Vuex.Store({
  state: {
    testArray: []
  },
  mutations: {
    setTestArray(state, data) {
      state.testArray = data
    }
  },
  actions: {
    getJsonData({
      commit
    }, countriesDrop) {
      if (countriesDrop && countriesDrop !== '') {
        fetch(`https://jsonplaceholder.typicode.com/${countriesDrop}`, {
            method: "GET"
          })
          .then(response => {
            return response.json();
          })
          .then(json => {
            commit('setTestArray', json)
          })
          .catch(err => {
            console.log(err);
          });
      }
    }
  }
})

new Vue({
  el: "#app",
  store,
  computed: {
    getDataFromStore() {
      return this.$store.state.testArray
    }
  },
  methods: {
    getData(countriesDrop) {
      this.$store.dispatch('getJsonData', countriesDrop)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3b5b6a6bb83f0edf2edf1">[email protected]</a>/dist/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click="getData('todos')">GET TODOS</button>
  <button @click="getData('albums')">GET ALBUMS</button>
  <ol>
    <li v-for="data in getDataFromStore">{{data.title}}</li>
  </ol>
</div>

The essence of incorporating Vuex into your Vue application lies in its centralized role. This enables you to manage the application state, handle both synchronous and asynchronous operations through actions and mutations, and have all components rely on the state as the primary source of truth.

Therefore, incoming input from a component triggers the dispatch of an action available within the Vuex store. If the action necessitates altering the state, a corresponding mutation method is invoked. By following this structured approach, reactivity across components utilizing the shared state is maintained.

In the provided example, I utilized a computed property to access data from the Vuex store, although getters could serve the same purpose.

This architectural design helps in preventing the cluttering of components with functions and data that should ideally reside within the store.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to initiate a change event using JavaScript?

I am attempting to enable my 4th checkbox automatically when there is a new value in the textbox (myinput). If the textbox is empty, I want to disable it. Currently, you have to tab out before the change event is triggered. Also, how can I check for an e ...

Exploring the world of Restify: Mastering the art of sending POST

Having trouble reading the body of a request while trying to create an API with Restify. Snippet from main.js: 'use strict'; const perfy = require('perfy'); perfy.start('startup'); const restify = require('rest ...

The combination of Vue init and Firebase init led to the creation of intricately nested

My project journey began with Vue CLI, generating the usual package.json, setting up node_modules, and so on. Next, I initiated a Firebase project in the same directory using firebase init, opting for functions. This action birthed a new folder called fun ...

Error encountered in Angular: FormBuilder provider not found

I am currently utilizing Angular 9. An error that I am encountering is as follows: No provider for FormBuilder This issue has been documented in numerous instances, with the common solution being to include the FormsModule in the app.module.ts file. F ...

AngularJS: How to accurately retrieve the offsetTop value upon page initialization

Issue: I am facing difficulty in obtaining the accurate top offset value of a DOM element immediately after the page has loaded. In the project I am currently working on, it is essential to retrieve the offsetTop value of various DOM elements as soon as ...

Guide to utilizing AJAX to retrieve a value from a controller and display it in a popup

I need assistance with retrieving data from a controller and displaying it in an HTML pop-up when a button is clicked. Currently, the pop-up shows up when the button is clicked, but the data is not being loaded. I would like the values to be loaded and d ...

Issues with jQuery code functionality within web forms

After creating a jQuery script to alter the CSS of a table row, I tested it on JSFiddle and it worked perfectly. However, when implemented into my web project, it doesn't seem to be functioning as intended. See the code below: HTML: <script src ...

Steps to run a function for updating a JSON data file

I currently have a Leaflet map displaying weather data retrieved from a Json source. There is already a function in place that updates the data every x minutes using setInterval. setTimeout(function () { refreshId = setInterval(function () { ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Failed to load Gulpfile.js in the Task Runner Explorer of Visual Studio 2019 version 16.6.2

Displayed below is the result in the output error window. Failed to execute "D:\TortSVN\Oil Diversity\Main Web App\LatsetOildiversity\Gulpfile.js"... cmd.exe /c gulp --tasks-simple fs.js:27 const { Math, Object } = primordials; ...

How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

Leveraging external JavaScript libraries in SAPUI5

I'm currently facing an issue while trying to include an external .js file in my SAPUI5 Controller. jQuery.sap.includeScript("externalLibrary.min.js", function() { // initializing objects from the library }); Despite setting up ...

Having trouble getting a div to slide to the left on hover and collapse on mouseout using Jquery?

Hey there! I need some assistance in completing this code snippet. I have a div with overflow:hidden and a margin-left of 82px. Inside it, there is a share link and a ul list containing three external links. When I hover over the share link, everything w ...

Bringing in d3js into Angular 2

Is there a way to successfully import d3js into an Angular2 project? I have already installed d3js using npm and added it to my systemJs, but am encountering a traceur.js error. I also attempted to just use the latest cdn in a script tag and tried import * ...

The 'slide.bs.carousel' event in Bootstrap carousel is triggered just once

Take a look at my JavaScript code: $('#carousel-container').bind("slide.bs.carousel", function () { //reset the slideImg $('.slideImg',this).css('min-height', ''); //set the height of the slider var ...