0

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
3
  • What does the data structure look like in the response of the /all-reviews API? Commented Jan 5, 2021 at 3:46
  • stackoverflow.com/questions/56957014/… Commented Jan 5, 2021 at 3:51
  • I figured it out - when setting state it was meant to be setReviews(allReviews.data) instead of setReviews(allReviews) Commented Jan 5, 2021 at 3:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.