Home > OS >  How to update lists after delete a category
How to update lists after delete a category

Time:01-30

I want to update the Category list after delete a category, I used custom hook for fetching data from the server. I'm not sure how to update state on custom fetch hook

const {data, error, loading} = useFetch("/api/admin/category");
    const [category, setCategory]= useState([]);

    useEffect(() => {
        setCategory(data)
    },[])

    const deleteHandler = (id) => {

        const deleteRequest = async () => {
            const data = await axios.delete(`/api/admin/category/${id}`);
            return data;
        }

        deleteRequest()
            .then(res => {
                data.filter((item) => {
                    return id !== item.id;
                })
            })
    }

CodePudding user response:

Adding data as the dependency to the useEffect hook may help, try this,

    const {data, error, loading} = useFetch("/api/admin/category");
    const [category, setCategory]= useState([]);

    useEffect(() => {
        setCategory(data)
    },[data])

    const deleteHandler = (id) => {

        const deleteRequest = async () => {
            const data = await axios.delete(`/api/admin/category/${id}`);
            return data;
        }

        deleteRequest()
            .then(res => {
                data.filter((item) => {
                    return id !== item.id;
                })
            })
    }

CodePudding user response:

in your custom hook add data to your dependency array;

in your component instead of the folowing

useEffect(() => {
  setCategory(data)
},[])

try to use the spread operator

useEffect(() => {
  setCategory([...data])
},[data])

CodePudding user response:

could you add you're custom hook to the code provided? and also be a bit more specific with your query?

import {useEffect, useState} from "react";
import axios from "axios";

const useFetch = (url) => {

    const [data, setData,isLoading] = useState([]);
    const [error, setError] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        request_get()
        .then(res => {
            if (res.request.status === 200) {
                setTimeout(() => {
                    setLoading(false)
                    setData(res.data.data)
                },1000)
            }
        })

        return () => {
            setData([]);
        }
    }, [])

    const request_get = async () => {
        const data = await axios.get(url)
        return data;
    }

    return {data: data, error: error, loading:loading}

}

export default useFetch;

enter image description here

  •  Tags:  
  • Related