Last active
February 6, 2023 09:03
-
-
Save mushfiqweb/4e0985b8d20b48c7851292d0e90c6736 to your computer and use it in GitHub Desktop.
Simple Example of Redux Toolkit using TypeScript, React and extraReducers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| import { useSelector, useDispatch } from 'react-redux'; | |
| import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; | |
| interface User { | |
| id: number; | |
| name: string; | |
| } | |
| const fetchUser = createAsyncThunk('users/fetchUser', async (id: number) => { | |
| const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`); | |
| return response.json(); | |
| }); | |
| const userSlice = createSlice({ | |
| name: 'users', | |
| initialState: { | |
| user: null as User | null, | |
| loading: false, | |
| error: null, | |
| }, | |
| reducers: {}, | |
| extraReducers: (builder) => { | |
| builder.addCase(fetchUser.pending, (state) => { | |
| state.loading = true; | |
| }); | |
| builder.addCase(fetchUser.fulfilled, (state, action) => { | |
| state.user = action.payload; | |
| state.loading = false; | |
| }); | |
| builder.addCase(fetchUser.rejected, (state, action) => { | |
| state.error = action.error.message; | |
| state.loading = false; | |
| }); | |
| }, | |
| }); | |
| const UserPage: React.FC = () => { | |
| const dispatch = useDispatch(); | |
| const { user, loading, error } = useSelector((state) => state.users); | |
| const handleFetchUser = (id: number) => { | |
| dispatch(fetchUser(id)); | |
| }; | |
| return ( | |
| <div> | |
| <button onClick={() => handleFetchUser(1)}>Fetch User</button> | |
| {loading && <p>Loading...</p>} | |
| {error && <p>Error: {error}</p>} | |
| {user && ( | |
| <div> | |
| <p>Name: {user.name}</p> | |
| </div> | |
| )} | |
| </div> | |
| ); | |
| }; | |
| export default UserPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment