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?
>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)