Home > other >  Uncaught TypeError: Cannot read properties of null - React.js
Uncaught TypeError: Cannot read properties of null - React.js

Time:07-06

const deletePerson = (persons) => {
axios
  .delete(`http://localhost:3001/persons/${persons.name}`)
  .then(console.log(`done`))
  .then(response => response.data)
  .then(setPersons(Object.values(persons).filter(q => q.name !== false)))}

I am a newbie in React.js. I have a problem, which I have been trying to solve for a couple of days. I added the Button for Delete requests, and in the different ways, it returns the same type of mistake: Uncaught TypeError: Cannot read properties of null (reading 'name').

error message

the use-case in that I am using this Button inside the resulting method, which automatically filters the list of persons:

const Filter = (props) => {return (<> {props.persons.filter(person => person.name.toLowerCase().includes(props.showFiltered.toLowerCase())).map((filteredName, id) => (
    <li key={id.toString()}>
      {filteredName.name} {filteredName.number} <Button text='delete' handleClick={props.deletePerson} />
    </li>  
  ))}  
</>)}

CodePudding user response:

Looks like you are using array values based on the entire object and not the persons value inside the object. And from the looks of it you are trying to find a name with the value false which doesn't seem to match what you have there.

Something like this is probably what you are looking for

.then(setPersons(Object.values(personsList).filter(q => q.name !== persons.name)))}

CodePudding user response:

TLDR;

const deletePerson = (persons) => {
  axios
    .delete(`http://localhost:3001/persons/${persons.name}`)
    .then(console.log(`done`))
    .then((response) => response.data)
    .then(setPersons(persons["persons"].filter((q) => q.name !== false)));
};

Explanation:

Using Object.values(persons) will return nested array which look something like this:

[
  [
    { "name": "Arto Hellas", "number": "040-123456", "id": 1 },
    { "name": "Ada Lovelace", "number": "39-44-5323523", "id": 2 },
    { "name": "Dan Abramov", "number": "12-43-234345", "id": 3 },
    { "name": "Mary Poppendieck", "number": "39-23-6423122", "id": 4 }
  ]
]

However, you're expecting q variable to be:

[
  { "name": "Arto Hellas", "number": "040-123456", "id": 1 },
  { "name": "Ada Lovelace", "number": "39-44-5323523", "id": 2 },
  { "name": "Dan Abramov", "number": "12-43-234345", "id": 3 },
  { "name": "Mary Poppendieck", "number": "39-23-6423122", "id": 4 }
]

Therefore, there are two ways of fixing this:

  1. Extracting the nested array Object.values(persons) => Object.values(persons)[0]

  2. Access the object value directly Object.values(persons) => persons["persons"]

  • Related