0

My code is straight forward and it looks like I am using list as the local state and have updated it once data are fetched, the list is perfectly loading on the tbody but still is undefined inside handleDelete

const [list, setList] = useState([]);

useEffect(async () => {
    fetchData();
}, []);

 async function fetchData() {
    const { data } = await supplier.listSupplier();
    setList(data.data);
}

const confirmDelete = (id) => {
    alertify.confirm(() => {
        handleDelete(id);
    });
};

const handleDelete = async (id) => {
    console.log("list>>", list); //returning undefined
    const originalList = list;
    const list = list.filter((r) => r.id !== id); // throwing Cannot read property 'filter' of undefined
    setState(list);
    try {
        await supplier.deleteSupplier(id);
        alertify.success("Successfully Deleted");
    } catch (ex) {
        if (ex.response && ex.response.status === 404) {
            toastify.error("Already Deleted.");
        }
        setState(originalList);
    }
};

return(
    
     <tbody>
        {list &&
            list.map((row, i) => (
                <tr key={row.id}>
                    <td>
                            <button
                                className="btn btn-danger btn-xs"
                                title="Delete"
                                onClick={() => confirmDelete(row.id)}
                            >
                                <i className="fas fa-trash"></i>
                            </button>
                    </td>
                </tr>
            ))}
    </tbody>

)

Here, on handleDelete() its throwing error throwing Cannot read property 'filter' of undefined and its obvious that list seems to be undefined down there. How could I fix this?

Aayush Dahal
  • 856
  • 1
  • 17
  • 51

1 Answers1

0

looks like a naming issue. PLease check the comment inside the code.

const handleDelete = async (id) => {
    const originalList = list;

//here i don't suggest updating list on this way
//as list is the state and setState is the way to go
//next thing I have changed is that I created newList instead of list again
    const newList = originalList.filter((r) => r.id !== id); 
    //also it looks like you have named setList while defining the state
    setList(newList);
    try {
        await supplier.deleteSupplier(id);
        alertify.success("Successfully Deleted");
    } catch (ex) {
        if (ex.response && ex.response.status === 404) {
            toastify.error("Already Deleted.");
        }
        setList(originalList);
    }
};
Saroj Shrestha
  • 2,696
  • 4
  • 21
  • 45