TypeError: Cannot read properties of undefined (reading '0') Axios API React

Viewed 23

So, I read all the other StackOverflow questions and I can't wrap my head around what I'm doing wrong.

I need to fetch and display the images from an API, which is on level Collection {object} > Items [array] > id {object} > links [array] > id {object} > href (url of image) in the json (https://images-api.nasa.gov/search?q=apollo)

(See screenshot of json viewer)

enter image description here

When I run my code, it gives an error in the console and the fetch is not working:

TypeError: Cannot read properties of undefined (reading '0') at DataFetching.js:16:1

Here is my code so far:

import React, {useState, useEffect} from "react";
import axios from "axios";

function DataFetching(){
    const [galaxies, setGalaxies] = useState();
    const [id, setId] = useState('apollo')
    const [idFromButtonClick, setIdFromButtonClick] = useState('apollo')

const handleClick = () => {
    setIdFromButtonClick(id)
}

useEffect(() => {
    axios.get(`https://images-api.nasa.gov/search?q=${idFromButtonClick}`)
        .then(res => {
            console.log(res.data.collection.items.links[0].id)
            setGalaxies(res.data.collection.items.links[0].id)
        })
        .catch(err => {
            console.log(err)
        })
}, [idFromButtonClick])

return (
    <div>
        <input type="text" value={id} onChange={e => setId(e.target.value)} />
        <button type="button" onClick={handleClick}>Fetch</button>
        <br />

        {galaxies?.map(galaxies => <div key={galaxies.id}>
            <img src={galaxies?.href} alt="" />
        </div>)}
    </div>
)
}

export default DataFetching

Here is the sandbox: https://codesandbox.io/s/react-axios-9b5nti?file=/DataFetching.js

0 Answers
Related