I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data:

export default new Vuex.Store({
  state: {
    user_data: util.fetch_user_data('username')
    ...
  }

located in the util.js file:

util.fetch_user_data = function(username){
   Lml_http('get', Api_urls.productconfig_common.user_data(username), null, response => {

    return response.data  // data is obtained here, as shown in the debugger.
  }, error => {

  })
}

However, when attempting to use the user_data from the state, it returns as undefined.


EDIT-1

I aim to utilize the fetch_util method in the store.js file for data retrieval and commit to the state.

EDIT-2

The code snippet for the lml_http function is provided below:

var lml_http = function (method, url, params, success_cb, error_cb, multipart_formdata=undefined) {

  var format_to_form_data = function(data){

    let formData = new FormData()
    for (let item in data) {
      formData.append(item, data[item])
    }
    return formData
  }

  var lowercase_method = method.toLowerCase()

  var formated_params = params

  var header_config = null

  if (multipart_formdata) {
    header_config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }

    formated_params = format_to_form_data(formated_params)
  }

  if(lowercase_method === "get") {

    formated_params = {params: formated_params}

    if (!header_config) {

      Axios.get(url, formated_params).then(response => {
        success_cb(response)
        return
      }).catch(response => {
        error_cb(response)
        return
      })
    } else {
      Axios.get(url, format_to_form_data(formated_params), header_config).then(response => {
        success_cb(response)
        return
      }).catch(response => {
        error_cb(response)
        return
      })

    }

    return
  }
  else {


    if(!header_config) {

      Axios[method](url, formated_params).then(response => {
        success_cb(response)
      }).catch(response => {
        error_cb(response)
      })
      return
    }else {
      Axios[method](url, formated_params, header_config).then(response => {
        success_cb(response)
      }).catch( response => {
        error_cb(response)
      })
      return
    }

  }

}

Answer №1

To get the user data, you can create an action like this:

export default new Vuex.Store({
  state: {
    user_data: null
  },
  mutations: {
    setUserData(state, data) {
      state.user_data = data;
    }
  },
  actions: {
    fetchUserData({ commit }, username) {
      Lml_http(
        "get",
        Api_urls.productconfig_common.user_data(username),
        null,
        response => {
          commit("setUserData", response.data);
        },
        error => {}
      );
    }
  }
});

Next, you need to dispatch this action in the created() hook of the root Vue instance.

//main.js

new Vue({
  el: "#app",
  store,
  render: h => h(App),
  created() {
    this.$store.dispatch("fetchUserData", "username");
  }
});

`

Edit:

By default, Axios returns a Promise. Here's how you should handle Axios calls within lml_http:

var lml_http = function(
  method,
  url,
  params,
  success_cb,
  error_cb,
  multipart_formdata = undefined
) {
  // Function to format data to FormData
  var format_to_form_data = function(data) {
    let formData = new FormData();
    for (let item in data) {
      formData.append(item, data[item]);
    }
    return formData;
  };

  var lowercase_method = method.toLowerCase();

  var formated_params = params;

  var header_config = null;

  if (multipart_formdata) {
    header_config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };

    formated_params = format_to_form_data(formated_params);
  }

  if (lowercase_method === "get") {
    formated_params = { params: formated_params };

    if (!header_config) {
      return Axios.get(url, formated_params)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    } else {
      return Axios.get(url, format_to_form_data(formated_params), header_config)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    }
  } else {
    if (!header_config) {
      return Axios[method](url, formated_params)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    } else {
      return Axios[method](url, formated_params, header_config)
        .then(response => {
          success_cb(response);
        })
        .catch(response => {
          error_cb(response);
        });
    }
  }
};

Don't forget to add a return statement in utils.js as shown below:

util.fetch_user_data = function(username){
   return Lml_http('get', Api_urls.productconfig_common.user_data(username), null, response => {

    return response.data  // Fetch and return the data
  }, error => {

  })
}

In your action fetchUserData, update it to:

fetchUserData({ commit }) {
    util.fetch_user_data('username').then((
      commit("setUserData", response.data);
    });
}

In main.js, simply dispatch the action without providing any payload:

//main.js

new Vue({
  el: "#app",
  store,
  render: h => h(App),
  created() {
    this.$store.dispatch("fetchUserData", "username");
  }
});

Answer №2

Due to the asynchronous nature of the fetch api, it will generate a promise instead of directly providing the response data. One potential approach could be:

const dataStore = new Vuex.Store({
  state: {
  userData: null,
  ...
};

util.fetchUserData('username')
  .then(user => dataStore.userData = user);

export default dataStore;

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

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...

Incorporate a variable into a function by integrating it

I'm struggling to accurately calculate the total hours needed based on the method of transportation. This code represents my initial attempt at learning how to code, diving into JavaScript for the first time. Here's my script: $(document).read ...

Pass information from a child component to a parent component within a React.js application

Using the Semantic-UI CSS Framework, I have implemented a dropdown menu and want to be able to select an item from it and identify which item has been selected. While I can determine the selected item within the child component and set its state, I am faci ...

What are the steps to showcase a webcam stream in GLSL by leveraging Three.js?

One method of displaying a webcam video using ThreeJS involves creating a video texture, as shown below: video = document.getElementById( 'video' ); const texture = new THREE.VideoTexture( video ); texture.colorSpace = THREE.SRGBColorSpace; const ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Combining backend webpack with Vue-CLI 3 for seamless integration

As I work on a full-stack application with Vue-CLI 3, the backend side is built in TypeScript which requires compilation. Currently, I am running the backend app directly using ts-node, but I am looking for a cleaner solution to bundle the backend code int ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

CSS and JavaScript Nav Menu Collapse (No Bootstrap)

I have written a navbar code using pure HTML/SASS, but I am facing a challenge in adding a collapse element to the navigation bar. Despite trying various solutions from Stack Overflow, I still haven't found one that works for me. Therefore, I am rea ...

Issue with ion-content on Ionic app not scrolling down when keyboard is displayed on an Android device

Currently, I am facing an issue with a basic view that contains a login form. When the keyboard pops up on Android devices, the content does not scroll up to ensure it remains visible above the keyboard. I have diligently followed the Keyboard instruction ...

Display the Slug in the Website URL upon clicking on a Blog Post using Angular and Strapi framework

When a user clicks on a blog, I want the URL to display the slug instead of the ID. My frontend framework is Angular and I have created a service to fetch data from the backend built with Strapi. Currently, when selecting a blog from the view, the URL disp ...

Use JavaScript to swap out various HTML content in order to translate the page

I am currently facing a challenge with my multilingual WordPress website that utilizes ACF-Field. Unfortunately, WPML is not able to translate the field at the moment (2nd-level-support is looking into it). As a solution, I have been considering using Java ...

Preventing Click Events during Data Fetching in React.js without Using jQuery

In the redux store, there is a state called isFetching. When data is being fetched from the backend, this state becomes true. I need to disable all click events when isFetching is true, without using jQuery. I stumbled upon some solutions (involving jQuer ...

I am trying to map through an array fetched from Firebase, but despite the array not being empty, nothing is displaying on the

I retrieved an array of products from a firebase database using the traditional method: export const getUsersProducts = async uid => { const UsersProducts = [] await db.collection('products').where("userID", "==", uid).get().then(sn ...

Unable to Modify TextField Component in React

Is it possible to attach variables to TextField and have those variables deleted as a whole and not editable? Check out the Codesandbox example HERE code <CardContent> <Autocomplete value={values.variable} options={variables} ...

Is it possible to swap out the content within a <div> element with an external piece of HTML code using JQuery or JavaScript whenever the viewport dimensions are adjusted?

<html> <head> </head> function () { var viewportWidth = $(window).width(); if (viewportWidth < 700) { $('#wrapper').load('A.html'); }; <body> &l ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...