I'm making a GET request from a my App react component, but I'm having trouble rendering the returned data.
I'm making an GET request with axios, and then setting the returned data to a state variable called reviews :
useEffect(() => {
axios.get('http://localhost:3000/all-reviews')
.then((allReviews) => {
setReviews(allReviews)
})
},[])
I checked React dev tools in the browser, and found that the data (an array of four objects) had indeed been set to state:
State:
{config: {…}, data: Array(4), headers: {…}, request…}
data:
[{…}, {…}, {…}, {…}]
status:
200
statusText:
"OK"
headers:
{access-control-allow-origin: "*", content-length: …}
config:
{adapter: ƒ xhrAdapter() {}, data: undefined, heade…}
request:
{DONE: 4, HEADERS_RECEIVED: 2, LOADING: 3, OPENED: …}
new entry:
""
Effect:
ƒ () {}
To access the data, I logged reviews.data to the console, which yielded [object Object],[object Object],[object Object],[object Object]
However when I tried to map through this data, I got the following error:
Uncaught TypeError: Cannot read property 'map' of undefined
So, how do I access the properties within the returned object?
Here's the react component in full:
import React, {useState, useEffect} from 'react'
import axios from 'axios'
const App = () => {
const [reviews, setReviews] = useState([])
useEffect(() => {
axios.get('http://localhost:3000/all-reviews')
.then((allReviews) => {
setReviews(allReviews)
})
},[])
// console.log(`this is reviews state: ${reviews && reviews.data && reviews.data[0].title}`)
console.log(`this is reviews state: ${reviews.data}`)
return (
<>
<h1>React development has begun!</h1>
{
reviews.data.map(item => {
<h2>{item.title}</h2>
})
}
</>
)
}
export default App
And here's the Schema/Model for the documents being returned:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const reviewSchema = new Schema({
userName:String,
stars:Number,
title:String,
photo:String,
blurb:String
}, {timestamps:true})
const Review = mongoose.model('review', reviewSchema)
module.exports = Review
/all-reviewsAPI?setReviews(allReviews.data)instead ofsetReviews(allReviews)