What is the best way to update data by making API calls within store.js using Vuex?

I am in the process of integrating vuex into my project. I have familiarized myself with mutations and actions for updating state properties. My main inquiry is regarding the most secure and effective method to update state components by retrieving data from an API. For instance:

Store.js

export default {
    state {
        prop1:'',
        prop2:''
    }

    actions {
        //What is the best approach for calling an API here and updating the values of prop1 and prop2
    }
}

Answer №1

Take a look at this snippet from my ongoing project. I've added comments to help clarify certain sections of the code:

import {
  PAGES_FIND,
  PAGES_FIND_ERROR,
  PAGES_FIND_SUCCESS,
} from '../mutation-types';
import { PagesAPI } from '../../api';

const state = {
  loading: false, // keeps track of loading status for display purposes
  error: null,    // stores and displays API errors
  pages: [],      // holds fetched pages
};

const mutations = {
  [PAGES_FIND](state) {
    state.loading = true;
  },
  [PAGES_FIND_SUCCESS](state, payload) {
    state.loading = false;
    state.error = null;
    state.pages = payload;
  },
  [PAGES_FIND_ERROR](state, payload) {
    state.loading = false;
    state.error = payload;
  },
};

const getters = {};
/**
 * AJAX calls are handled here using 'axios'
 */
const actions = {
  /**
   * Retrieves list of pages with optional params
   * @param {Function} [commit] - Commit function
   * @param {Object} [params={}] - Fetch parameters (e.g. filter, limit)
   * @returns {Promise}
   */
  fetchPages({ commit }, params = {}) {
    commit(PAGES_FIND); // show 'Loading...' message in UI
    return PagesAPI.find(params)
      .then(res => commit(PAGES_FIND_SUCCESS, res.data))
      .catch(err => commit(PAGES_FIND_ERROR, err));
  },
};

const namespaced = true;

export default {
  state,
  getters,
  mutations,
  actions,
  namespaced,
};

Implementation of PageAPI is shown below for clarity within the actions:

/* eslint-disable import/prefer-default-export */
import axios from 'axios';
import config from '../../config';

const ENDPOINT = `${config.service.baseUrl}/pages`;

/**
 * Function to retrieve pages
 * @param {Object} params
 */
export const find = params => (
  axios.get(ENDPOINT, { params })
);

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

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Retrieving dates from a database and populating them into a jQuery UI Picker using PHP

I need to retrieve dates from the database using PHP and highlight them in a datepicker. Here is how I am attempting to accomplish this: HTML Date: <input type="text" id="datepicker"> // Static dates // An array of dates var eve ...

How can I subtract a value from an array using node-js?

If we consider a simple scenario where an array totalSpots = [95] contains only one value, and a new booking is made, the goal is to automatically assign one parking spot to the user who booked it. This will involve reducing the value in the array by 1 or ...

The Node.js script functions correctly on the first run but encounters failure in subsequent executions

I am in need of a Node.js script that can perform the following tasks: 1 - Trigger when an image is added to a specific S3 bucket. 2 - Generate a thumbnail of that image (360x203 pixels). 3 - Store a copy of the thumbnail in a separate S3 directory. ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Choosing a String and Performing a Double Click in Selenium with Java

My textbox is disabled, and it includes the following attributes: <div id="writingactivityId2" class="boxSize ng-pristine ng-untouched ng-valid ng-valid-required redactor_editor writingActivityDisabled" ng-focus="editing()" redactor="" readonly="" ng- ...

Is there a feature in Vue.js similar to AngularJS' `ng-repeat-start` directive?

After going through vue.js documentation, I couldn't find any reference to a feature similar to ng-repeat-start / ng-repeat-end Is there a way to achieve something like this? <table> <tr class="weather_warning top" ng-repeat-start="warni ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

Using VueJS to iterate through an array while applying a condition to filter out certain elements (combining v-for with v-if)

I'm currently working on a v-for loop to display two columns of card elements. The idea is to print the current element and the next one in a row if the index is even, skipping the elements with odd indexes. This is what my code looks like: <temp ...

Is there a way to modify the maximum size limit for a POST request package?

I am encountering an issue while attempting to send an array of bytes using a POST request. In my server-side implementation, I am utilizing Node.js and Express.js. Unfortunately, I am receiving error code 413 or the page becomes unresponsive ('Payloa ...

What is causing my HTML to not recognize my Angular JS code?

Trying to dive into Angular JS, I wrote a small piece of code but for some reason, the HTML is not recognizing Angular JS. This is my index.html file: <!DOCTYPE HTML> <html ng-app="store"> <head> <link rel="stylesheet" type=" ...

Enhance scrolling with a bounce effect

My goal is to implement a smooth scrolling experience with a bounce effect when the user over-scrolls, meaning they scroll too much to the top or bottom. I found an answer on Stack Overflow that explains how to achieve smooth scrolling, but I also want to ...

Properly executing a for loop

I have devised a method to transform Swagger 1 documentation into Swagger 2. This involves utilizing an array of resources as input for the conversion process. However, I have encountered an issue where the code seems to be skipping ahead and jumping to ...

Incorporating D3's library functions into Rxjs for seamless integration with Observables

I'm really struggling with this concept and could use some guidance. My goal is to monitor when data is fetched, but I seem to have confused the process. Here's what I've tried so far: Using d3.tsv for an ajax request. var test = Rx.Observa ...

Prevent chunk files from being loaded using the bootstrap script

How can I prevent dynamically loading chunked CSS files after creating a production build in VueJs2? The issue at hand // Disabling mini-css-extract-plugin CSS loading var cssChunks = {"chunk-4f730675":1}; if(installedCssChunks[chunkId]) promise ...

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

Steps for integrating a universal loader in Angular

My implementation of a global loader is as follows: In the CoreModule: router.events.pipe( filter(x => x instanceof NavigationStart) ).subscribe(() => loaderService.show()); router.events.pipe( filter(x => x instanceof NavigationEnd || x in ...

The Redux state fails to start with the default initial state

I'm a newcomer to react-redux. In my reducer, I have the following structure: const initialState = { Low: [ { id: 0, technologyId: 0, technology: '', type: '', ...

Laravel VueJS Vuetable-2 without user authentication

Initially, I attempted all the solutions provided here and on other websites. What I have experimented with: Vuetable-2 not working with Laravel Passport Unable to retrieve data from using vuetable-2, in Vuejs 2 The Issue: I was working on a project (L ...