0

I'm fetching some data from a JSON file. I'm using the map method to display it and it's stored in a state. I need to be able to delete an item when the delete button is clicked. I'm using the filter method to filter out that specific item but I get this error: Uncaught TypeError: Cannot read properties of undefined (reading 'filter')

export default function Customers() {

const { appData, setAppData } = useContext(AppContext);
const { customers, packages } = appData;


function handleDeleteCustomer(id) {
    
    console.log(id)
    setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)
}

return (
    <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="simple table">
            <TableHead>
                <TableRow>

                    <TableCell >id</TableCell>
                    <TableCell >Name</TableCell>
                    <TableCell />
                    <TableCell />

                </TableRow>
            </TableHead>
            <TableBody>
                {appData.customers.map((row) => {
                    return (
                        <TableRow sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
                            <TableCell component="th" scope="row">{row.id}</TableCell>
                            <TableCell >{row.name}</TableCell>
                            <TableCell ><Button variant="contained">Create Invoice</Button></TableCell>
                            <TableCell ><Button variant="contained" onClick={() => handleDeleteCustomer(row.id)}>Delete</Button></TableCell>
                        </TableRow>
                    )
                })}
            </TableBody>
        </Table>
    </TableContainer>
)

}

1 Answer 1

1

There is a bug in your code:

setAppData(appData.customers.filter(customer => customer.id !== id), appData.packages)

not

setAppData(setAppData.customers.filter(customer => customer.id !== id), appData.packages)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Fixed it but still got an error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
I think you should check if customers is defined before doing ``` appData.customers.map(...)``` you can do it by simply adding this: ``` !appData.customers ? "no customers" : appData.cutomers.map(...) ```
It's defined as long as I don't click the button. The list of customers is rendered. When I click the delete button, then for some reason 'appData.customers' is not defined anymore.
I believe the error is coming from setAppData function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.