axios delete operation with use reducer in react js

335 views Asked by At

i am working on crud operation with context api and use reducer. i fetch data from an api and store it as initial value. but now i am confused how to delete a user from my fetched list. i made a remove function which works fine on manual refresh but does not auto refresh and gives back an error. how to make a delete function.

   const InitialState = {
  Users:  []
}

const Reducer = (state, action) =>
{
    switch(action.type)
    {
        case 'FETCH_USERS':
            return{
                Users: action.payload
            }
        case 'REMOVE_USER':
            return{

                Users: action.payload
            }
        default: 
        return state
    }
    
}
const GlobalContext = createContext(InitialState)

const GlobalState = ({children}) => {
    
    const [state, dispatch] = useReducer(Reducer, InitialState);

    useEffect(()=>
    {  
        fecthapi();
    },[])

    const fecthapi = async () =>
        {
           const res  = await axios.get('http://localhost:3002/users')
           dispatch({type: 'FETCH_USERS', payload: res.data})
        }
     
    const Remove = async  (id) =>
    {
        await  axios.delete(`http://localhost:3002/users/${id}`)
        dispatch({
        type: 'REMOVE_USER', payload: id
        
        })
       
    }
    return (
    <>
    <GlobalContext.Provider value = {{Users: state.Users, Remove: Remove}}>
        {children}
    </GlobalContext.Provider>
    </>
    )
}```
0

There are 0 answers