What is the best way to retrieve data from a REST API using Vuex store?

I am currently utilizing Vuex to manage the state of my application.

In order to retrieve data from a rest API via an Ajax Get request and display a list of objects, I am dispatching an action to fetch this data from the server. However, I am unsure how to properly handle it within the component.

Currently, my code looks like this:

//component.js
created(){
      this.$store.dispatch("fetch").then(() => {
        this.objs = this.$store.state.objs;
      })
    }

Although this works, I believe there might be a more efficient way to manage store data instead of directly assigning it to a local property.

Is there a better approach to handling this using mapState or any other method?

Thank you!

Answer №1

Discovering the right approach is a process of experimentation to find what suits you best. Here is my recommendation:

{ // the store
  state: {
    something: ''
  },
  mutations: {
    setSomething (state, something) {
      // an example of modifying before storing
      state.something = String(something)
    }
  },
    actions: {
      fetchSomething (store) {
        return fetch('/api/something')
          .then(data => {
            store.commit('setSomething', data.something)
            return store.state.something
          })
      })
    }
  }
}

{ // your component
  created () {
  this.$store
    .dispatch('fetchSomething')
    .then(something => {
      this.something = something
     })
    .catch(error => {
       // handle the error here!
     })
  }
}

For more detailed explanations, visit: https://vuex.vuejs.org/en/actions.html

If you are managing errors within the action itself, calling the action and using a computed property linked to the store value simplifies the process

{
  computed: {
    something () { // automatically updates
      return this.$store.state.something
    }
  },
  created () {
    this.$store.dispatch('loadSomething')
  }
}

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

The showdown between JSON and a hefty JavaScript array

Currently, I am developing a jQuery autocomplete feature that will need to handle between 10 to 20k records. The dataset is static, and I have the option to either retrieve it from a JSON file or embed it directly into the page using a single line of code ...

Error in Layout of Navigation Panel and Tabbed Pages

Working on a school project, I encountered a challenge. I found two useful solutions from the W3 website - a sticky navigation bar and the ability to include tabs on a single page for a cleaner presentation of information. However, when trying to implement ...

Exercises from the Shader Scriptures

This winter break, I have dedicated my time to delving into the world of shaders. I am currently faced with a challenging exercise: y = sin(x); Explore the exercises below and observe the results: Introduce time (u_time) into the equation before calcul ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

The vue-pdf component fails to update when the src attribute is modified

I've implemented the newest vue-pdf package to showcase pdf files in my application. I developed a component called PdfViewer: <template> <div class="fill-height pdf-container"> <template v-if="src && number ...

React modal image showing a misaligned image upon clicking

I recently integrated the react-modal-image library into my project to display images in a modal when clicked. However, I encountered an issue where the displayed image is off center with most of it appearing offscreen. I'm unsure what is causing this ...

organizing the div based on the given data

I'm working on developing a web application using HTML and AngularJS. There are two main div elements: Div 1 <div class="box1" style="margin-top:20px;"> <span ng-repeat="i in data" style="font-size:14px; font-weight:normal">{{i.div ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Passing a variable through an ajax request upon successful completion

Is there a way I can include the variable 'schedule_id[i]' in the result of this call? Can I also add this variable to the data object? Here's my code: for (var i = 0; i < schedule_id.length; i++) { //Making an AJAX request $.a ...

What steps can be taken to ensure a neutral value is returned in Mongodb aggregation when the specified attribute does not exist?

I need to create an aggregation that looks like this: Game.aggregate([{ $match: { "_id": { "$in": result.games } } ...

Creating a self-chaining function in JavaScript: A guide

Currently, my goal is to create an Array.prototype function called union( array_to_union ), and then utilize it in the following manner: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... I am aiming for the outcome to be the union of these arrays. ...

The slice() method in arrays provides a reference to the elements rather than copying

In my file, I am exporting an object in the following manner: export const LINECHART2_DATA = { series: [{ data: [], name: 'HR', }, { etc... }] } The way I import it is like this: import { LINECHART2_DAT ...

Switch up div containers with JavaScript based on the set array order of elements?

As I work on creating a list that calculates the sum of selected numbers, I encountered an issue with rearranging the items. Despite successful functionalities like adding images with names, changing languages, and performing calculations, the page keeps r ...

Identifying Inaccurate Device Date Using JavaScript

Is there a way to detect if the device's date is inaccurate using javascript? (For example, displaying an alert if the current date is 2016/6/16 but the device date is 2016/6/15) ...

Vue components/code disappearing upon import

I've double-checked the file path and it seems to be correct, but for some reason, the code in App.vue is not displaying. As a newcomer to Vue, I'm a bit lost as to what could be causing this issue. Any guidance or assistance would be greatly app ...

Selenium and C#: Issue with ExecuteAsyncScript command

Trying to execute JavaScript using Selenium Driver but encountering an exception stating that the input string is in an incorrect format. The provided path contains the necessary JavaScript function, which is essentially an onclick without parameters, re ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

I'm currently in the process of building a brand new React.js application by utilizing the command "npx create-react-app". However, upon completion, I encounter an error while attempting to run it with the command "npm start"

Below is the complete error message Error message from ./src/index.js at line 1, character 58 Failed to parse module: Unexpected token found at (1:58) The following loaders were used to process the file: * ./node_modules/@pmmmwh/react-refresh-webpack-pl ...

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

Switch Out DIV Tag After Clicking It Three Times

I am attempting to replace a specific div element with a different one after it has been clicked on 3 times. This is the sole task I am aiming to achieve through the code. I have searched for code snippets that accomplish this, but all of them immediately ...