Aaron
Aaron

Reputation: 4480

mapping with data from axios call using async await in react

I am able to get data back from my api call. But when I try to map it, I get an images.map is not a function. I consoled log the data to make sure it is an array

Here is my code

import { useState, useEffect, useRef } from "react";
import axios from "axios";
import DisplayData from "./DisplayData";

function Home() {
    const [images, setImages] = useState({});

    useEffect(() => {
        const getApi = async () => {
            const tempData =  await axios.get(
                "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=10&api_key="
            );
            setImages(tempData.data.photos);
            console.log(tempData.data.photos);
            console.log(images);
            // // console.log(typeof( images));
            images.forEach(element => {
                console.log(element);
            });
        };
        getApi()
    }, []);

    if (!images) {
        return <h1>Waiting</h1>;
    } else {
        return (
            <div>
                <h1>Home</h1>

                {images.map((item) => (
                    <DisplayData key={images.id} images={images} />
                ))}
            </div>
        );
    }
}
export default Home;

Upvotes: 0

Views: 198

Answers (1)

Cristian-Florin Calina
Cristian-Florin Calina

Reputation: 1008

It's because you initialize the images variable as an object. Objects do not have map method on their prototype and are also not falsy.

If you want it to not throw an error, initialize as an array (which does have the map function) or as a falsy value in order for the first if to be executed and be in the waiting state.

const [images, setImages] = useState(null); // or useState([])

Upvotes: 3

Related Questions