Home > Software design >  unable return data from promise to other component in react
unable return data from promise to other component in react

Time:04-13

I have an api posting data on server and i want to get that response in other file. this is a function in action.js file. I want to return response of this promise to other component where it is called.

export const saveOrder = data => dispatch => {
  fetch(`${baseUrl}/save-order`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(res => res.json())
    .then(json => {
      console.log('json1', json);
     **want to return this json variable**
      alert('order placed');
    })
    .catch(error => {
      console.log('error in saving', error);
    });
};

this is my component where i want to get its response when order is successfully placed. I have tried async and await but it did not worked.

  const postOrder = () => {
    var data = new FormData();
    data.append('userId', state.user.id);
    dispatch(saveOrder(data));
  };

CodePudding user response:

It looks like you are using redux for state management. However, you are not using the dispatch function to store the data received in saveOrder. Actually, all that your dispatch does is just call the necessary thunk, and already in it you must call dispatch with an action that will store the data in the store. Then directly in the component itself using selector you can get the data from the store when they are available. In general, you are using redux-thunk only to run an api request and not following the necessary concepts. You can see the usage model here: https://redux.js.org/tutorials/essentials/part-5-async-logic

CodePudding user response:

Would you like to try passing the Dispatch function as parameter?

Just in case your Redux-Saga has problems?

The way I would create this function would a bit different, separating the roles.

const saveOrder = data => {

  return fetch(`${baseUrl}/save-order`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(res => res.json())
    .then(json => {
      return "Success"
    })
    .catch(error => {
      return "Error"
    });
};


  
   saveOrder("any data")
    .then(result => console.log(result))
    .catch(error => console.log(error.message))
 

    /*Instead of console.log you can place your dispatcher*/
  • Related