Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In React axios.get is fetching the correct response.data but the console is not logging any response.data._id

useEffect(() => {
  setLoading(true);
  axios
    .get(`http://localhost:5555/books/${id}`)
    .then((response) => {
      setBook(response.data);
      console.log(response.data);
      console.log(response.data._id);
      setLoading(false);
    })
    .catch((error) => {
      console.log(error);
      setLoading(false);
    });
}, [id]);

This is my code to get the data from the books data base
in the first console log console.log(response.data) the console is logging

data: {
  _id: '6539fb91dee8e9f4440d9bca', 
  title: 'Scarlet', 
  author: 'JamesHowlatt', 
  publishYear: 2000,
  __v: 0
}

but the second console log console.log(response.data._id) is logging undefined why?
i understand that the setBook State wont be updated immediately but why is the response.data._id undefined?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for better visualization try:

console.log(response);

there is probably a data object inside data object like this:

data: {
  data: {
    _id: '6539fb91dee8e9f4440d9bca', 
    title: 'Scarlet', 
    author: 'JamesHowlatt', 
    publishYear: 2000,
    __v: 0
  }
}

therefore to console.log _id you need to do:

console.log(response.data.data._id)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading