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
-
Is this use case not the one described in the redux-thunk documentation in combination with the fetch api or axios?sn42– sn422019-04-25 06:23:30 +00:00Commented Apr 25, 2019 at 6:23
-
the redux-thunk documentation have described only about fetch api calls and not post call.. i need to hit a post api call here :)Surya Flash– Surya Flash2019-04-25 06:33:49 +00:00Commented Apr 25, 2019 at 6:33
-
The Fetch API covers post requests, too. The intention of my comment was to show you that async requests (async actions, you looked for that) are documented and it requires minimal effort to apply the samples to your situation. Because you didn't provide any source or any kind of specific problem (other than "i need todo this"), and the answer is pretty basic, the only answer u get are people implementing it for you in little lines of code, not the kind of question for SO in my view.sn42– sn422019-04-25 07:56:56 +00:00Commented Apr 25, 2019 at 7:56
1 Answer
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.