0

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;
3
  • Are you sure that images is really an array and not maybe an array inside an object? Commented Jul 13, 2022 at 20:14
  • 1
    First - change your const [images, setImages] = useState({}); to const [images, setImages] = useState([]);. Second - setImages does not update images immediately, so console.log(images); just after set will not write down new values Commented Jul 13, 2022 at 20:17
  • ^ yep, and a solution for this is to write another useEffect with dependency on images and do your forEach there (if you indeed want to do something after it changed). Commented Jul 13, 2022 at 20:22

1 Answer 1

3

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([])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.