Aug 29, 2024
npm install react-redux @reduxjs/toolkit
src folder, create a new folder named redux.store.jsx in the redux folder.configureStore
configureStore from @reduxjs/toolkit.const store = configureStore({
reducer: {
todo: todoSlice.reducer
}
});
todoSlice.jsx in the redux folder.createSlice and createAsyncThunk from @reduxjs/toolkit.isLoading, data, and error.createSlice to define the slice with reducers and asynchronous actions:
const todoSlice = createSlice({
name: 'todo',
initialState: {
isLoading: false,
data: [],
error: false
},
reducers: {},
});
export const fetchTodo = createAsyncThunk('todo/fetchTodos', async () => {
const response = await fetch('API_URL_HERE');
return response.json();
});
main.jsx, wrap the application with Provider and pass the store:
import { Provider } from 'react-redux';
import store from './redux/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Todo.jsx.useDispatch and useSelector hooks from react-redux.useEffect to dispatch the fetchTodo action:
useEffect(() => {
dispatch(fetchTodo());
}, [dispatch]);
if (isLoading) {
return <h1>Loading...</h1>;
} else {
return data.map(todo => <p key={todo.id}>{todo.title}</p>);
}