You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Step - 3: Create typed hooks to use in inside components to share states - store/hook.ts
import{TypedUseSelectorHook,useDispatch,useSelector}from'react-redux';importtype{RootState,AppDispatch}from'./store';// Use throughout your app instead of plain `useDispatch` and `useSelector`exportconstuseAppDispatch: ()=>AppDispatch=useDispatch;exportconstuseAppSelector: TypedUseSelectorHook<RootState>=useSelector;
Step - 4: Create query api as a custom hook - store/services/name_api.ts
import{createApi}from'@reduxjs/toolkit/query/react';importaxiosfrom'axios';constbaseUrl='http://localhost:5000/';exportinterfaceIPost{id: number;title: string;body: string;}constfetchPost=async()=>{returnawaitaxios.get(baseUrl);};constcreatePostData=async(payload: {title: string;body: string})=>{returnawaitaxios.post(baseUrl,payload);};constdeletePostData=async(id: number)=>{returnawaitaxios.delete(baseUrl+id);};exportconstpostApi=createApi({reducerPath: 'postApi',baseQuery: fetchPost,tagTypes: ['Post','User'],endpoints: (builder)=>({getPost: builder.query<IPost[],void>({query: ()=>'/',// transformResponse: (res: IPost[]) => res.slice(0, 10), // transform the Response as your needprovidesTags: ['Post'],// which tagsType use for}),createPost: builder.mutation({query: createPostData,invalidatesTags: ['Post'],}),deletePost: builder.mutation({query: deletePostData,invalidatesTags: ['Post'],}),}),});exportconst{ useGetPostQuery, useCreatePostMutation, useDeletePostMutation }=postApi;
Step - 4: update the store file in every api create ==> Add to reducer and middleware
import{useGetPostQuery,useCreatePostMutation,useDeletePostMutation,}from'../store/features/postApi';constPosts=()=>{/// data fetching hookconst{ isLoading, data, refetch }=useGetPostQuery();// create new data hookconst[createPost]=useCreatePostMutation();constcreateNewPost=async()=>{constnewPost={title: 'new title'+Date.now(),body: 'body'+Date.now(),};awaitcreatePost(newPost);refetch();};// delete post hookconst[deletePost]=useDeletePostMutation();constdeletePostHandler=async(id: number)=>{awaitdeletePost(id);refetch();};return(<div>{isLoading &&<h1>Loading...</h1>}<ulclassName='list'>{data?.map((item)=>(<likey={item.id}><span>{item.id}-{item.title}</span><buttononClick={()=>deletePostHandler(item.id)}>X</button></li>))}</ul><div><buttononClick={createNewPost}>AddPost</button></div></div>);};exportdefaultPosts;
To use slice create slice and add to store - store/feature/name_slice.ts
import{createSlice,createAsyncThunk}from'@reduxjs/toolkit';importtype{PayloadAction}from'@reduxjs/toolkit';importaxiosfrom'axios';interfaceUser{name: string;email: string;}interfaceInitialState{users: null|User[];isLoading: boolean;error: null|string;}constinitialState: InitialState={users: null,isLoading: true,error: null,};// Async thunk to fetch users from the APIexportconstfetchUsers=createAsyncThunk('users/fetchUsers',async(id)=>{try{constresponse=awaitaxios.get(`https://jsonplaceholder.typicode.com/users?id=${id}`);returnresponse.data;}catch(error){thrownewError('Failed to fetch users');}});constuserSlice=createSlice({name: 'users',
initialState,reducers: {},extraReducers: (builder)=>{builder.addCase(fetchUsers.pending,(state)=>{state.isLoading=true;}).addCase(fetchUsers.fulfilled,(state,action: PayloadAction<User[]>)=>{state.isLoading=false;state.users=action.payload;}).addCase(fetchUsers.rejected,(state,action)=>{state.isLoading=false;state.error=action.error.message||'Error To Fetch user';});},});exportdefaultuserSlice.reducer;