I am trying to fetch data in react from mongodb using axios, I receive an array of objects on applying the GET method, but I am unable to store data in a state properly and use the data from the state in desired form, I want to fetch a particular ker's value here i.e. title. Please help me to solve this or suggest a better way of doing this.
[state, setState] = useState()
useEffect( async () =>
{
axios({
"method": "GET",
"url": "http://localhost:5500/api/add/",
"headers": {
"Content-Type": "application/json",
}
})
.then((response) => {
setState(response.data)
})
.catch((error) => {
console.log(error)
})
const title = state[1].title
console.log(title)
}, state)
The data is stored in mongodb as an array of objects having key:value pairs, I received following output when I used input - console.log(response.data[1].title)
output- title-2
for data object:
1: {_id: "5f6e10d3509b062528381884", title: "title-2", details: "details-2", __v: 0}
After that, when I used console.log(state[1].title)
i received
TypeError: Cannot read property 'title' of undefined while trying to access data from an array of objects
i think you are asking for
state[1].title
before axios returns the data and save it to the state. if it that the case its means youstate
isunderfined