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

The MaterialUI table pagination feature is experiencing an issue where the "Next" button is

Every time I attempt to search for a record with a lower value, such as 6, 14, 19, or 20, the Next button does not become active. However, when dealing with larger records, it functions perfectly fine. I am uncertain about what mistake I might be making. ...

When using JSON.stringify, the output is null. However, when using document.write, the data

I am currently working on a plugin for crawljax that involves executing some JavaScript code, similar to the following: String result = browser.executeJavaScript(script).toString(); The script code is as follows: function getElementPosition(id) { var el ...

Enhance User Experience with a Responsive Website Dropdown Menu

Currently, I am focused on enhancing the responsiveness of my website and I realized that having a well-designed menu for mobile view is essential. To address this need, I added a button that only appears when the screen size is 480px or lower, which seems ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

We have encountered an issue with the syntax in the code: ajaxsample/update_agenda. It seems to be an unrecognized expression according to

Here's the code for updating my controller: public function update_agenda() { $id= $this->input->post('did'); $this->load->model('agenda_model'); $data = array ( ...

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

Learn how to cycle through three different texts that appear in the same spot using smooth transitions

I am working with three different rows that contain the Typography component. My goal is to display the first row, followed by the second, then the third, and back to the first one in a continuous loop. All three rows should be shown in the same location, ...

unable to retrieve JSON sub-elements

I encountered an issue while attempting to iterate through the JSON object provided. When trying to access the content-items using page.content-items, I received an error message. Is it possible to access an object that has a key with "-" in its name? Co ...

What is the most effective method for discerning the availability of fresh data?

Many highload websites are able to notify their users of new messages or topics in real-time without the need for page refreshing. How do they achieve this and what approaches are commonly used? There appear to be two main methods: Continuously querying ...

PHP code in Wordpress incorporating an Ajax request

Does anyone know how to fetch user data as a string using ajax in WordPress? I think I understand the basic concept PHP This code goes in my functions.php file add_action('template_redirect', 'edit_user_concept'); function edit ...

Installing external Javascript libraries on Parse cloud code can be done by following these steps

Currently, I have integrated these JavaScript libraries into my Parse cloud code. var request = require('request'); var fs = require('fs'); var Twit = require('twit'); However, the code refuses to compile if these libraries ...

Navigate through fabricated data not appearing in Express application

I have come across a handlebars template file within my Express app: {{#each data}} <article class="id-{{this.id}}"> <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1> <p>{{this.body}}</p> </ar ...

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Vuetify displaying incorrectly following deployment

After creating a spa with vue.js for the frontend, I utilized the vuetify library for various components and layout. While everything looked great locally, upon deploying to Azure, all vuetify styling seemed to disappear. My custom css was still applying ...

The Ajax readyState consistently displaying a value of 0

I am encountering an issue with my Ajax code as it always returns 0 when I access 'readyState'. I have not been able to identify the source of the problem yet. Any assistance on this matter would be greatly appreciated: var xhr = null; function ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Vue Array Proxy Class Fails to Trigger Reactivity

My custom Array extension has a feature where it intercepts changes made to its properties using Proxy, which is returned from the constructor. However, when used in a Vue component, it encounters issues. For example, when a filter is added, the display do ...

Converting a functional component into a class-based component

I am in the process of converting a functional based Component to a class-based Component and creating a PrivateAuth Component. Here is the original PrivateAuth functional Component. function PrivateRoute({ component: Component, ...rest }) { return ( ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...