Reputation: 21
I have recently switched from redux to redux toolkit. I understand basic state management but I dont know how to make an (axios) post request to my backend with the state data as a payload.
Upvotes: 1
Views: 4779
Reputation: 358
You may have a slice like this:
import {createSlice, } from '@reduxjs/toolkit';
export const initialState = {
todos: [],
loading: false,
errorMessage: null,
};
const slice = createSlice({
name: 'todos',
initialState,
reducers: {
loadTodos(state) {
state.loading = true;
state.errorMessage = null;
},
loadTodosError(state, action) {
state.loading = false;
state.errorMessage = action.payload.message;
},
loadTodosSuccess(state, action) {
state.loading = false;
state.errorMessage = null;
state.todos = action.payload.data
},
},
});
export const {actions, reducer} = slice;
and given that redux toolkit comes with a 'special' function called 'createAsyncThunk' that is usually used with async actions, you can call it like this:
import axios from 'axios';
import {createAsyncThunk} from '@reduxjs/toolkit';
export const loadTodos = createAsyncThunk(
'loadTodos',
async (_, thunkAPI) => {
const response = await axios.get('http://todos.com/api', 'delete');
thunkAPI.dispatch(actions.loadTodosSuccess(response.data));
return response;
});
then all you have to do is to import the actions and dispatch them like this
import {useDispatch, useSelector} from 'react-redux';
import {loadTodos} from './slice';
const TodoList = () => {
const dispatch = useDispatch;
useEffect(() => {
dispatch(loadTodos());
}, [dispatch]);
const {isLoading, errorMessage} = useSelector(state => state.todos);
return (
<div>
{isLoading && <Spinner />}
{errorMessage && <span>Failed to load todos</span>}
{todos.map(todo => (
<div>{todo}</div>
))}
</div>
);
};
Upvotes: 2