Mohammad
Mohammad

Reputation: 85

undefined when accessing context value

i get this error :

Cannot read properties of undefined (reading 'forEach') which refers to genre context in home component :

genre.genres.forEach((element)=> {.....

the problem goes away after i refresh so many times , i guess the home component is rendered before data is fetched from the api and passed to the state . how to fix this ?

app

import * as api from "./api"
import { useState, useEffect } from 'react';
import { createContext } from 'react';
import Home from './components/Home'

export const PopularMovies = createContext();
export const Genre = createContext();

function App() {

    const [popular, setPopular] = useState([])
    const [genre, setGenre] = useState([])

    async function getPopular() {
        const popular = await api.getPopular()
        setPopular(popular.results)
    }
    async function getGenre() {
        const genre = await api.getGenre()
        setGenre(genre)
    }

    useEffect(() => {
        getPopular()
        return () => { //tried this,didnt fix it
            setPopular([])  
        };
    }, []);
    
    useEffect(() => {
        getGenre()
        return () => {  //tried this,didnt fix it
             setGenre([])
        };
    }, []);

    return (
       <PopularMovies.Provider value={popular}>
            <Genre.Provider value={genre}>
                <Home key={1} />
            </Genre.Provider>
        </PopularMovies.Provider>
    );}

export default App;

home

import React from 'react'
import { useContext } from 'react'
import { PopularMovies } from "../App.js"
import { Genre } from "../App.js"

export default function Home() {

    const value = useContext(PopularMovies);
    const genre = useContext(Genre);

    const findGenre = () => {
              genre.genres.forEach((element) => { // error starts here
                ...     
    return (
        ...
    )}

Upvotes: 0

Views: 85

Answers (1)

Lahcen
Lahcen

Reputation: 1423

It's better checking if your the object "genre" and the array 'genres' are not undefined before executing forEach function; like this

const findGenre = () => {
              genre?.genres?.forEach((element) => { // error starts here
                ...     
    return (
        ...
    )}

Upvotes: 1

Related Questions