Home > Net >  mapping with data from axios call using async await in react
mapping with data from axios call using async await in react

Time:07-14

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;

CodePudding user response:

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([])
  • Related