Home > Net >  Calling the property of an object returns object instead of property
Calling the property of an object returns object instead of property

Time:12-22

The title of this is admittedly confusing, but that's because i barely understand what's happening enough to describe it.

I have a react app which is suppose to list the first 5 pictures the mars rover has taken on sol 1000 using the NASA API.

The API returns an object in the format of Object{photos[0-999].img_src}. I slice object.photos to make a new object (or array, not sure) consisting of the first 5 items of the photos array within the object, but each of the items is itself an object containing various data about the image, when all i need is the image url.

To get the url, i use the .map method to create a new array and assign the url's of each item to it.

Finally, i use the .map method again to display each of images by inserting the url into the image source.

However, the inspector tools how that instead of each element source being the url string, they are all '[object Object]'.

I have no idea what is happening, why it's happening, or what to do to stop it. Can anyone shed light on this?

import "./App.css"
import { useState } from "react"

const App = () => {
  const [data, setData] = useState([])

  const handleFetch = async () => {
    const response = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=${process.env.REACT_APP_NASA_KEY}`, {
      method: "GET",
    })
    const fetchData = await response.json()
    const fetchData2 = fetchData.photos.slice(0,5)
    setData(fetchData2.map(arrayItem => {
      return arrayItem.img_src
    }))

  }
  
  return (
    <div className="App">
      <h1>Mars rover images</h1>
      <button onClick={handleFetch}>Click me</button>
      <ol>
        {data && 
          data.map((temp, index) => {
            return (
              <li key={index}>
                <img src={{temp}} alt="" />
              </li>
            )
          })}
      </ol>
    </div>
  )
}


export default App

CodePudding user response:

You should use temp like below.

<img src={temp} alt="" />

not {{temp}}

  • Related