Skip to content Skip to sidebar Skip to footer

How To Get Normal Json Object From Promise Object In React-redux

How to get normal JSON object from Promise Object in react-redux? My action.js contains: export function allEmp() { let url = 'employees?access_token='; let result =

Solution 1:

react-redux does not support asynchronous action creators out-of-the-box, so you'll need to add a dependency to your project.

Take a look at the redux-thunk middleware, which adds support for asynchronous action creators.

The idea with redux-thunk is that your action creator will trigger another action once the asynchronous code resolves.

In your case, you would have an allEmp action creator that calls another action receiveAllEmp once the Promise resolves:

allEmp Action Creator (using redux-thunk)

export function allEmp() {

    return (dispatch) => {

        return ApiCall.getApiCall(url).then((response) => {

            // Dispatch the receiveAllEmp action

            dispatch(receiveAllEmp(response));

            return response;
        });
    };
}

receiveAllEmp Action Creator (normal action creator)

export function receiveAllEmp(response) {
    return {
        type: "ALL_EMP",
        payload: response,
    };
}

Solution 2:

Promises represent asynchronous processes whose may not be available immediately. They provide a way to trigger a handler when the result is ready (so your Javascript can go on and get other work done).

To access their result, you place a handler in a .then method which is called at resolution and receives the result as an argument.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

You might consider writing your function:

export function allEmp() {
  p = new Promise();

  let url = "employees?access_token=";
  ApiCall.getApiCall(url)
  .then(function (response) {
     console.log("result",result);    
     p.resolve({
                type: "ALL_EMP",
                payload: response})
            })
   .catch(function (error) {
      console.log("error",error);  
     p.reject(error)
   });

 return p  // allEmp now returns a promise which gives it a .then() method to contain your handler code.
 }

Then call your function like this:

allEmp().then(
 function(res){/*handle it here, not called until async resolves, receives result*/},
 function(err){/*or resolves to error, receives error*/}
 )

You might consider also having a look at the await/async syntax which makes it appear as if you code is waiting for async operations and can enhance readability in the majority of cases.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


Post a Comment for "How To Get Normal Json Object From Promise Object In React-redux"