Surya Flash
Surya Flash

Reputation: 27

How to implement post api calls using thunk middleware in react-redux?

I was working with redux-thunk and superagent npm for jwt authentication and i would want to know how to implement post calls using thunk-middleware in the actions.js file and not in the main reducer.js file

Upvotes: 0

Views: 1400

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15698

There's a couple of different ways to go about it, but I personally like to use the axios library. Axios essentially just assists with making an API request and parsing the data back from the API into json.

In your actions.js file.

export const authenticateUser = () => {
 return (dispatch, getState) => {
    //get the token from the reducer 
    const jwtToken = getState().jwtTokenReducer.tokenKey
    axios.post("/api/authenticate-user", jwtToken) //jwtToken passed into request
       .then((res) =>){
           dispatch({
              type: "AUTHENTICATE_USER",
              payload: res.data
           })
       }
       .catch((errors) => {
            dispatch({
               type: "ERRORS",
               payload: errors.response.data
            })
        })
 }
}

So take a look at the above syntax. Typically when you define an action-creator, you setup a function that returns an action (object). But thanks to redux-thunk, you can now setup your action-creators to return functions with dispatch as an argument.

So in your returned function you can define certain logic, like making a request to an API like we did up there. Then we can take that data by using the .then promise handler and use it as a payload for an action that we would explicitly dispatch to our reducers.

Upvotes: 1

Related Questions