Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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([])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading