Home > Mobile >  React / NextJS - how can this be a „Cannot read properties of null" error?
React / NextJS - how can this be a „Cannot read properties of null" error?

Time:12-02

I have a NextJS application which conditionally renders a set of data tables using useState and useEffect:

const [board,setBoard] = useState("AllTime");

const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false);
const [TrendingCreatorLeaderboardVisible, setTrendingCreatorLeaderboardVisible] = useState(false);
const [TrendingVideoLeaderboardVisible, setTrendingVideoLeaderboardVisible ] = useState(false)

useEffect(() => {
  board === "AllTime"
    ? setAllTimeLeaderboardVisible(true)
    : setAllTimeLeaderboardVisible(false);
  board === "TrendingVideo" ? setTrendingCreatorLeaderboardVisible(true) : setTrendingCreatorLeaderboardVisible(false);
  board === "TrendingCreator" ? setTrendingVideoLeaderboardVisible(true) : setTrendingVideoLeaderboardVisible(false);
}, [board]);

const handleOnChange = (e: { target: { value: SetStateAction<string>; }; }) => {
  setBoard(e.target.value);
};

The tables visibility is then controlled through a dropdown element:

 <select id ="dropdown" value={board} onChange={handleOnChange} className="mb-5 rounded-full bg-black px-6 py-3 duration-100 ease-in hover:bg-white hover:fill-black hover:text-black w-80 text-3xl tracking-tight font-work">
    <option value="AllTime">All Time</option>
    <option value="TrendingVideo">Trending Video</option>
    <option value="TrendingCreator">Trending Creator</option>
</select>

{AllTimeLeaderboardVisible && <AllTimeLeaderboard />}
{TrendingVideoLeaderboardVisible && <TrendingVideoLeaderboard />}
{TrendingCreatorLeaderboardVisible && <TrendingVideoLeaderboard />}

While I have set „AllTime" as the first option Value, NextJS is giving me a

TypeError: Cannot read properties of null (reading 'useState')

Error which is pointing to:

 const [board,setBoard] = useState('AllTime');

How can this be a property of null?

CodePudding user response:

Check that you are importing useState correctly e.g.

import { useState } from 'react';

If that doesn't solve it, check out the comments under this similar SO question which points to it being a configuration issue.

CodePudding user response:

My error was in making an invalid hook call, by not calling the function inside the body of the function component.

  • Related