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

Issue found within triggered hook: "TypeError: Unable to retrieve property '$http' as it is undefined"

Hey there, I've created a userInfo() function to fetch user data and utilize it in different areas. How can I effectively call this function to retrieve the necessary information? Can anyone assist me with this issue? export function getUserInfo () { ...

What could be causing the error message "rawModule is undefined" to appear when attempting to add Vuex modules?

While exploring Vuex modules for the first time, I faced some difficulties. The console error message "rawModule is undefined" had me puzzled as there was not much information available on it. So, let me share with you the problem I encountered and how I ...

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

Guide to updating passwords with passport-local-mongoose

After successfully importing the passport-local-mongoose to my code and being able to register and log in users, I now face the challenge of changing the password for a specific user. How can I achieve this? According to the documentation of passport-local ...

Loading Google Maps with Ajax

Exploring the world of google maps has been quite entertaining for me, however, I find myself in need of some assistance. The issue at hand involves a small block of HTML/Javascript that can be seamlessly integrated into a standard HTML page or loaded into ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...

Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original fo ...

What is the process for sending a JSON response and then redirecting to an HTML page after a successful event in Node.js using Express?

Trying to send a JSON response and redirect the page simultaneously in Express.js. Need help figuring out how to achieve this. Is it possible to redirect in Express.js while sending a JSON response to the client? The goal is to use this JSON data to render ...

JavaScript library designed for efficient asynchronous communication with servers

Looking for a lightweight JS library to handle AJAX cleanly and simplify basic DOM selections on our website (www.rosasecta.com). Currently, we're manually coding a lot of Ajax functionality which is not only ugly but also difficult to manage. We&apos ...

Create a function that generates an HTML string and returns it to be used in JSX

As a newcomer to JSX/React, I am seeking guidance on removing inline code. I have created a function that returns the value to be displayed in the template/JSX. The function works well except when it needs to return a string along with an element like a Li ...

Validation of New Relic License Key

Is there a way to verify the validity of a provided New Relic license key in a JavaScript application? I have searched through the documentation but did not come across any API endpoint for this purpose. UPDATE: Just to clarify, we do not have access to ...

Tips for successfully typing the backtick character when transitioning to Typescript:

I am currently working on a Typescript Vue project involving Leaflet. I came across some code for lazy-loading map markers, but it was written in Javascript. Although the code works fine, I keep receiving errors and warnings from VSCode because this is not ...

Encountering a Bad Request Response When Trying to Access WCF Service via Jquery Ajax

Encountered an issue when trying to call a WCF web service using jQuery Ajax, resulting in a bad request error without clear insight into the root cause. The service is not triggering any methods - neither success nor failure. Both the web service and the ...

Efficiently transferring components of a JavaScript project between files

For the first time, I am creating an npm package using ES6 and Babel. However, I am facing difficulties in connecting everything together so that it can be imported correctly by the end user. The structure of my build (output) folder is identical to src: ...

The typical initial default argument to be passed to the function using fn.apply

Recently, I discovered the power of using fn.apply() in JavaScript to store function calls with all their arguments intact for future use. In my specific situation, I don't require the first argument, which is the context (this), and I want to find a ...

The options object provided for Ignore Plugin initialization in Webpack 5.21.2 does not conform to the API schema, resulting in an error

Here is the setup of my webpack.config.js on a backend server running webpack version 5.21.1: /* eslint-disable */ const path = require('path'); const webpack = require('webpack'); module.exports = { target: 'node', modul ...

What are some effective strategies for incorporating multiple Themes into an AngularJS project?

Currently, I am in the process of working on a project that involves utilizing AngularJS, UI Bootstrap, and Sass. The next step is to incorporate different themes that can be selected by the user. While I have successfully implemented the ability to apply ...

Sometimes jQuery may require multiple executions with just one click

Content of index.php <script type="text/javascript" src="//<?php echo $_SERVER["SERVER_NAME"];?>/javascript/jquery-1.10.2.min.js" ></script> <script type="text/javascript"> $(document).ready(function() { $( document ).on( 'c ...

The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking) I'm really trying to wrap my head around the life cycle of request and response objects. Take a look at the following co ...