I have been using Redux-Toolkit
more than the React-Redux
. I came across situations where I had to make GET
requests, So I recently started using Redux-Thunk
(before this I used useEffect
but, as it's not a standard way to handle async
functions, when using redux. I learned about middleware
).
Here is the code of my Thunk function
nad extraReducer
which handles the GET
request
export const fetchData = createAsyncThunk("type/getData", async () => {
try {
const response = await axios({url});
return response.data;
} catch (error) {
console.log(error.response);
}
});
export const extraReducers = {
[fetchData.pending]: (state) => {
state.loading = true;
},
[fetchData.fulfilled]: (state, action) => {
state.loading = false;
state.products = action.payload;
},
[fetchData.rejected]: (state) => {
state.loading = false;
state.error = true;
},
};
In fetchData
function my returned response.data
is being used in extraReducers
as payload
so I can set the state easily. But, now the scenario is I have make a post request and I don't know how will I send the data to my Thunk
function.
First you create the action of posting data and send the data
:
export const postData = createAsyncThunk(
"type/postData",
async (data) => {
try {
const response = await axios.post("https://reqres.in/api/users", data);
// If you want to get something back
return response.data;
} catch (err) {
console.error(err)
}
}
);
Then in a place where you want to send that data you just dispatch this action with the data
argument that you want to send:
const handlePost = () => {
// whatever you want to send
const data = .........
dispatch(postData(data));
}
If you want, you can also modify your extraReducers
for this action.