Home > Blockchain >  × TypeError: Cannot read properties of null (reading 'map')
× TypeError: Cannot read properties of null (reading 'map')

Time:12-08

I didn't understand why I got this error TypeError: Cannot read properties of null (reading 'map'), it's a very simple feature. I hope that someone could help me.

This is my code, and I can't map the object from the API request. For privacy, I modified the key of the API request.

import { useEffect, useState } from "react";

export default function Featured() {

    const [featured, setFeatured] = useState(null);

    useEffect(() => {
        fetch('https://api.rawg.io/api/games?dates=2021-01-01,2021-12-31&ordering=-rating&key=1234')
        .then(response => response.json())
        .then(data => {
            console.log(data.results.slice(0, 4));
            setFeatured(data.results.slice(0, 4));
        });
    }, []);


    return (
        <div className="container mt-5">
            <div className="row">
                {featured.map((el) => {
                    return (
                        <div>{el.name}</div>
                    )
                })}
            </div>
        </div>
    );
}

CodePudding user response:

Your issue is because you started your data out as null. On initial render before the api has a chance to come back your featured array is actual null and you cannot call .map on null. Instead you can either start the data off as an empty array like so

const [featured, setFeatured] = useState([]);

Or you can have a check in your render to make sure its no longer null which will be the case after the api comes back with a response.

  • Related