Lectures List
capscom technology computer course almora

Redux Toolkit Query CRUD api

  • src
    • apis
      • UserApi.js
    • components
      • AddUserComponent.js
      • UpdateUserComponent.js
      • UserComponent.js
    • features
      • slices
        •  UserFormSlice.js
  • store
    • store.js
  • app.js
  • index.js

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {store} from './store/store';
import {Provider} from 'react-redux';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
import Register from './Pages/Register';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  // <React.StrictMode>
    <Provider store={store}>      
      <BrowserRouter>
        <Routes>
          <Route path='/' element={<App/>}/>
          <Route path='/register' element={<Register/>}/>
        </Routes>
      </BrowserRouter>
    </Provider>
  // </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

App.js

import logo from './logo.svg';
import './App.css';
import UserComponent from './components/UserComponent';
import AddUserComponent from './components/AddUserComponent';
import {useSelector, useDispatch} from 'react-redux';
import { addFormAction} from './features/slices/UserFormSlices';
import UpdateUserComponent from './components/UpdateUserComponent';
import Template from './Layout/Template';

function App() {

  console.log("App loaded");

  const addingForm=useSelector(state=>state.users.addingForm)
  const editingForm=useSelector(state=>state.users.editingForm)
  const dispatch= useDispatch();

  return (
    <>
    <Template>
      <div className="container mx-auto border-4 border-teal-300 w-full md:w-1/2 p-3 rounded-2xl">
        {addingForm?<AddUserComponent/>:null}
        {!addingForm?
        <button 
        className="bg-rose-500 rounded px-8 py-2 text-white mb-2"
        type="button" onClick={()=>dispatch(addFormAction())}>Add</button>
        :null}   

        {editingForm?<UpdateUserComponent/>:null}
        

        <UserComponent/>
      </div>     
    </Template> 
    </>    
  );
}

export default App;

UserApi.js

import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query/react';
export const UserApi=createApi({
    reducerPath:'user-api',
    baseQuery:fetchBaseQuery({baseUrl:'http://127.0.0.1:8000/api/'}),
    tagTypes:["users"],
    endpoints:(builder)=>({
        getUsers: builder.query({
                query:(page=1)=>`/users?page=${page}`,
                transformResponse:(response, meta, arg)=>{
                    return{
                        data: response?.data?.data,
                        lastPage: response?.data?.last_page
                    }
                },
                providesTags:["users"]
            }),
        deleteUser: builder.mutation({
            query:(id)=>({
                url:`/users/${id}`,
                method:'DELETE'
            }),
            invalidatesTags:["users"]            
        }), 
        addUser: builder.mutation({
            query:(data)=>({
                url:`/register`,
                method:'POST',
                body:data
            }),
            invalidatesTags:["users"]            
        }), 
        updateUser: builder.mutation({
            query:({id,...data})=>({
                url:`/users/${id}`,
                method:'PUT',
                body:{
                    name:data.name,
                    email:data.email
                }
            }),
            invalidatesTags:["users"]            
        }),        
    }),
})
export const {useGetUsersQuery, 
    useDeleteUserMutation, 
    useAddUserMutation,
    useUpdateUserMutation
}=UserApi;

AddUserComponent.js

import { useState } from "react";
import { useAddUserMutation} from '../apis/UserApi';

import {addFormAction, editFormAction} from '../features/slices/UserFormSlices';
import {useDispatch} from 'react-redux';

let AddUserComponent=()=>{
    let [addUser]=useAddUserMutation();
    let [name, setName]=useState("");
    let [email, setEmail]=useState("");
    let [password, setPassword]=useState("");

    let addHandler=()=>{
        console.log(name, email, password);
        addUser({
            name:name, 
            email:email,
            password:password
        });
    }

    return(
        <>
        <div className="mb-2 w-full md:w-1/2 border-4 p-2 rounded-2xl mx-auto">
            <div className="mb-2">
                <label htmlFor="name">Name</label>
                <input type="text" className="w-full block border-2 p-2 rounded" onChange={e=>setName(e.target.value)} />
            </div>

            <div className="mb-2">
                <label htmlFor="email">Email id</label>
                <input onChange={e=>setEmail(e.target.value)} type="text" className="w-full block border-2 p-2 rounded"/>
            </div>

            <div className="mb-2">
                <label htmlFor="password">Password</label>
                <input onChange={e=>setPassword(e.target.value)} type="text" className="w-full block border-2 p-2 rounded"/>
            </div>            

            <div className="mb-2 text-center">
                <button 
                onClick={addHandler}
                type="button" className="p-2 border-2 px-8 rounded-2xl">Add</button>
            </div>
        </div>
        </>
    )
}
export default AddUserComponent;

UpdateUserComponent.js

import { useEffect, useState } from "react";
import { useUpdateUserMutation} from '../apis/UserApi';
import {addFormAction, editFormAction} from '../features/slices/UserFormSlices';
import {useSelector, useDispatch} from 'react-redux';

let UpdateUserComponent=()=>{    

    console.log("update user component");

    let [name, setName]=useState("");
    let [email, setEmail]=useState("");

    const dispatch = useDispatch();
    let [updateUser]=useUpdateUserMutation();

    var id=useSelector((state)=>state.users.id);
    var nameToEdit=useSelector((state)=>state.users.name);     
    var emailToEdit= useSelector((state)=>state.users.email);
    
    useEffect(()=>{
        setName(nameToEdit);
        setEmail(emailToEdit);
    },[nameToEdit, emailToEdit]);

    

   
 

    let updateHandler=()=>{        
        updateUser({
            id:id,
            name:name, 
            email:email
        });
    }

    return(
        <>
        <div className="mb-2 w-full md:w-1/2 border-4 p-2 rounded-2xl mx-auto">
            <div className="mb-2">
                <label htmlFor="name">Name({nameToEdit})</label>
                <input onChange={(e)=>setName(e.target.value)} value={name} type="text" className="w-full block border-2 p-2 rounded"  />
            </div>

            <div className="mb-2">
                <label htmlFor="email">Email id({emailToEdit})</label>
                <input onChange={(e)=>setEmail(e.target.value)} value={email} type="text"  className="w-full block border-2 p-2 rounded"/>
            </div>           

            <div className="mb-2 text-center">
                <button 
                onClick={updateHandler}
                type="button" className="p-2 border-2 px-8 rounded-2xl">Update</button>
            </div>
        </div>
        </>
    )
}
export default UpdateUserComponent;

UserComponent.js

import { useState } from 'react';
import { useDeleteUserMutation, useGetUsersQuery} from '../apis/UserApi';
import {useDispatch} from 'react-redux';
import { editFormAction } from '../features/slices/UserFormSlices';
let UserComponent=()=>{

    console.log("user component");

    let dispatch = useDispatch();
    
    const [page, setPage]=useState(1);           
    const {data, error, isLoading, isSuccess}= useGetUsersQuery(page); 
    
    const [deleteUser] = useDeleteUserMutation();

    const deleteItem=(id)=>{
        if(window.confirm("Are you sure to delete user?")){
            deleteUser(id);
        }
    }


    if(isLoading){
        return(<div>Loading...</div>);
    }
    if(!data){
        return(<div>No posts:(</div>);
    }
       

    return(
        <>
        <div className=''>
        { isSuccess?data?.data.map((user)=>{
                return(
                    <div 
                    className="border-2 p-2 mb-2 w-full rounded-xl flex justify-between"
                    key={user.id}>
                        <div className='flex flex-col'>
                            <div>{user.name}</div>
                            <div>{user.email}</div>
                        </div>                        
                        <div className='flex flex-col space-y-2'>
                            <button 
                            onClick={()=>deleteItem(user.id)}
                            type="button" 
                            className='bg-red-500 text-white rounded-xl px-2 py-1'>Delete</button>  
                            <button 
                            type="button"
                            className='bg-blue-400 text-white rounded-xl px-2 py-1'
                            onClick={()=>dispatch(editFormAction(user))}
                            >Edit</button>                      
                        </div>
                    </div>
                )
            }): null}

{page>1?<button className="ring-2 px-4 mx-2 py-1 rounded-xl" type="button" onClick={()=>setPage(page-1)}>Previous</button>:null}
{page<data?.lastPage?<button type="button" className="ring-2 px-4 py-1 rounded-xl" onClick={()=>setPage(page+1)}>Next</button>:null}
            </div>
        </>
    )
}
export default UserComponent;

UserFormSlices.js

import { createSlice } from "@reduxjs/toolkit";
const initialState={    
    id:null,
    name:"",
    email:"",    
    addingForm: false,
    editingForm: false
};
export const UserFormSlices=createSlice({
    name:'users',
    initialState,
    reducers:{
        addFormAction:(state)=>{
            state.addingForm=true;
            state.editingForm=false;
        },
        editFormAction:(state, action)=>{            
            state.editingForm=true
            state.addingForm=false;
            state.id= action.payload.id;
            state.name = action.payload.name;
            state.email = action.payload.email;
        },
    }
});
export const {addFormAction, editFormAction}=UserFormSlices.actions;
export default UserFormSlices.reducer;

store.js

import {configureStore} from '@reduxjs/toolkit';
import { UserApi } from '../apis/UserApi';
import UserFormReducer from '../features/slices/UserFormSlices';
export const store = configureStore({
    reducer:{
        users:UserFormReducer,
        [UserApi.reducerPath]: UserApi.reducer
    },
    middleware: (getDefaultMiddleware)=>getDefaultMiddleware().concat(UserApi.middleware)
});
Author/Written by: Mr Hemant Singh (Founder)
Terms & Conditions CAPSCOM TECHNOLOGY Pvt. Ltd. का बेहतर रूप से संचालन करने के लिए यहॉ कुछ नियमें और शर्ते लागू है अगर आप कैप्सकॉम टैक्नोलॉजी में पढ़ रहे है तो यह आप पर लागू होता है।