Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables:

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 visibility of the tables is controlled by 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 />}

When setting "AllTime" as the first option value, I encountered an error in NextJS:

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

This error specifically points to the line:

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

How can this be a property of null?

Answer №1

The mistake I made was attempting an improper hook call, failing to execute the function within the function component itself.

Answer №2

Ensure that you have implemented the import of useState correctly, like so:

import { useState } from 'react';

If this does not resolve the issue, consider reviewing the responses in this related question on Stack Overflow which suggests a possible configuration error.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

The "variable" used in the React app is not defined, resulting in a no

Following the tutorial of Mosh Hamedani, I attempted to create a react-app. You can watch the tutorial here. I followed his instructions exactly as mentioned. I encountered an issue when trying to pass an argument named product to a function called on on ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

"Experience the seamless navigation features of React Navigation V6 in conjunction with

Hello there, I've been experimenting with react-navigation 6 in an attempt to show a modal with presentation: "modal" as instructed on the documentation. However, I'm facing an issue where the modal is not displaying correctly and appears like a ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

Enhancing react-to-print functionality for optimal performance across various browsers and mobile platforms

Currently, I am developing a sample react-to-print resume template to be included in a larger portfolio website. While testing the page on Chrome and Edge browsers on a laptop, everything seems optimized. However, there are issues when using Firefox; the b ...

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

Utilizing Material UI to create a versatile and adaptable grid layout

Is there a way to set the container direction as "row" above md size screens, and "column" below md size screens? How can I achieve this? <Grid container direction = "row"(in large screens)/direction = "column"(in small screens)> I have attempted th ...

I keep getting a 404 error when trying to use Internationalization (i18n) Routing

I want to implement multiple languages on my website using Next.js. I have made some configurations in next.config.js /** @type {import('next').NextConfig} */ const nextConfig = {} module.exports = nextConfig module.exports = { i18n: { l ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

A guide on utilizing the React Suite range slider in rsuite

Hello there, I recently started working with the UI framework rsuite (React suite) and everything was going smoothly until I tried to use the Range slider component's API. Unfortunately, I am facing some issues with the labels and tooltips not display ...

Unlawful use of the return statement

Can you identify the issue with this code? The browser reports: "Uncaught SyntaxError: Illegal return statement" I'm looking for an explanation in this format: 1 2 3fool 4 5bar 6fool 7 8 9bar... let arr = []; for (i = 0; i <= 100; i++) { if ( ...

How can you set a condition for when no matches are found in a list filter?

I recently came across a fascinating example on W3 Schools that taught me how to implement a search filter. Below, I have customized it for everyone's reference. I am interested in modifying it to only display a list item with the message: No matche ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

What is the best way to display images one by one from a map using a random fade effect?

I am in the process of creating a logo wall for a website. I successfully managed to display them randomly using a map, but now I want to make them appear one by one in a random order (for example: image 1, image 6, image 3, ...) and keep them visible once ...

Once an item is added, the table vanishes into thin air

I have a DataTables setup to show a list of project names, and I have a button that should add an item to the displayed array. However, when I click the button, the table disappears. Below is the code snippet: view.html <button ng-click="vm.add()"> ...