Warning: The `children` attribute returned a value of NaN

I am currently working on a tic tac toe web application. I encountered an issue when clicking the "Ver Ranking" button, as it displays a warning message that I'm unsure how to address:

Warning: Received NaN for the `children` attribute. If this is expected, cast the value to a string.
    at td
    at tr
    at tbody
    at table
    at div
    at div
    at Component /./src/app/ranking/page.js:20:82)

The web app is being developed using Next.js 14 and the code in my page.js file is as follows:

"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Button from "@/components/Button";
import { getRanking, updateRanking } from "@/lib/apiCalls";

const winCombs = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6],
];

export default function Home() {
  // rest of the component's code...
}

I have also created a ranking page with the following code:

"use client";

import Button from "@/components/Button";
import { useState, useEffect } from "react";
import { getRanking } from "@/lib/apiCalls";
import { useRouter } from "next/navigation";

export default function Component() {
  // rest of the ranking page component code...
}

The data displayed in the ranking table is fetched from a database using the getRanking method:

export const getRanking = async () => {
  try {
    // fetch request to retrieve ranking data...
  } catch (error) {
    console.log(error);
  }
};

I have attempted to modify the Button component but the warning persists. Could the useEffect() in the ranking page be causing this issue? Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

In the ranking page, I made some modifications to the code:

"use client";

import Button from "@/components/Button";
import { useState, useEffect } from "react";
import { getRanking } from "@/lib/apiCalls";
import { useRouter } from "next/navigation";
export default function Component() {
  const [ranking, setRanking] = useState({
    playerX: { won: 0, lost: 0, tied: 0 },
    playerO: { won: 0, lost: 0, tied: 0 },
  });
  const router = useRouter();
  useEffect(() => {
    const getRankingData = async () => {
      try {
        const rankingData = await getRanking();
        if (rankingData) {
          setRanking(rankingData);
        }
      } catch (error) {
        console.log("Failed to fetch ranking data:", error);
      }
    };

    getRankingData();
  }, []);

  const safeSum = (a, b, c) => {
    return (a || 0) + (b || 0) + (c || 0);
  };

  return (
    <div className="container mx-auto px-4 md:px-6 py-8">
      <div className="flex flex-col md:flex-row items-center justify-between 
mb-6">
        <h1 className="font-bold mb-4 md:mb-0">Ranking</h1>
      </div>
      <div className="border rounded-lg overflow-hidden">
        <table className="w-full table-auto">
          <thead>
            <tr>
              <th className="w-[200px] px-4 py-3 text-left font-
bold">Jugador</th>
              <th className="px-4 py-3 text-right font-bold">Victorias</th>
              <th className="px-4 py-3 text-right font-bold">Derrotas</th>
              <th className="px-4 py-3 text-right font-bold">Empates</th>
              <th className="px-4 py-3 text-right font-bold">PJs</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td className="px-4 py-3 font-medium">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-800 flex items-center justify-center">
                    <span>U</span>
                  </div>
                  <span>Usuario</span>
                </div>
              </td>
              <td className="px-4 py-3 text-right">{ranking.playerX.won}</td>
              <td className="px-4 py-3 text-right">{ranking.playerX.lost}</td>
              <td className="px-4 py-3 text-right">{ranking.playerX.tied}</td>
              <td className="px-4 py-3 text-right">
                {safeSum(ranking.playerX.won, ranking.playerX.lost, ranking.playerX.tied)}
              </td>
            </tr>
            <tr>
              <td className="px-4 py-3">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-800 flex items-center justify-center">
                    <span>IA</span>
                  </div>
                  <span>IA</span>
                </div>
              </td>
              <td className="px-4 py-3 text-right">{ranking.playerO.won}</td>
              <td className="px-4 py-3 text-right">{ranking.playerO.lost}</td>
              <td className="px-4 py-3 text-right">{ranking.playerO.tied}</td>
              <td className="px-4 py-3 text-right">
                {safeSum(ranking.playerO.won, ranking.playerO.lost, ranking.playerO.tied)}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <Button
        text="Volver a Jugar"
        action={(e) => {
          e.preventDefault();
          router.push("/");
        }}
      />
    </div>
  );
}

Kindly review this updated code for functionality.

Changes Made:
.....The ranking state now initializes with default values to prevent undefined issues.
.....Try-catch block added in getRankingData function to handle potential errors when fetching data.
.....SafeSum function ensures default to 0 if any values (won, lost, tied) are undefined.

If encountering errors, add console.log() statements for troubleshooting purposes.

If using TypeScript, assign type definitions to states to avoid compile-time errors. I hope these adjustments prove helpful.

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

Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed. Dynamic data: { "page": 2, "data" ...

Spooky results displayed on website from NightmareJS

Is there a way to display the output from nightmareJS onto a webpage when a button is clicked using HTML, CSS, and JS? This is my nightmareJS code: var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false}) nightmare .go ...

What is the best way to validate if fields are blank before sending a message using the button?

<template> <div> <div class="form-group"> <label for="name">First Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Ente ...

Adding up the numbers with JavaScript

Hello everyone, I've been working on some transformations and now I'm left with an array of objects: Can anyone help me come up with a flexible function that will generate a new object where each data[i] is the sum of values from the previous ob ...

There is an issue with transmitting data from an HTML page to the server and then retrieving data from the server

Upon running this code, I encountered an issue with sending and receiving data. I kindly request assistance in correcting my code. Highlighted below is the server-side code var http = require("http") ; var fs = require("fs") ; http.createServer(function( ...

Issue with incorrect date being retrieved in MongoDB response from a node server

My date in mongodb is structured as follows: ISODate("2020-08-03T00:00:00.000+05:30"), However, after querying the date, it appears like this: 2020-08-02T18:30:00.000Z I am looking to get the correct date of 2020-08-03. What could I be doing wr ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Excess space appearing at the right of my Next.js component

I'm currently diving into Next.js as I work on building out my portfolio. I have a solid foundation in HTML, CSS, and I've been honing my JavaScript skills through back-end development with Express.js. Check out this code snippet: export const W ...

Guide to positioning a THREE.js plane onto the exterior of a spherical object

Just starting out with Threejs and 3D graphics. I'm interested in learning how to position a plane of any dimensions on the surface of a sphere. Here's an example image of what I'm aiming for: example image ...

Lately, I've been coming across mentions of "myApp.controllers" and "myApp.modules" in Angular JS. Can anyone explain the significance of these terms?

Recently, I've come across code that looks like this: angular.module('app.controllers') This pattern has appeared in a few tutorials I've read. However, the purpose of the .controllers within the module name is unclear to me. I'v ...

Could someone please provide clarification on this specific JavaScript syntax? I am unsure about the usage of `const {

Although I am not very familiar with javascript, I have come across this syntax and I would greatly appreciate it if someone could help me understand it! Regarding Node.js const { check, validationResult } = require('express-validator/check') ...

Troubleshooting expressjs: Issues with serving Static Files

I've encountered a frustrating issue. Express js is not serving my static files as expected, and instead it keeps hitting my global catch all get handler. Here's how my directory structure looks: node/apps/web/app.js -------------/public/ ---- ...

I am not forcing the Angular module to conform to my perspective

Hello, I am new to Angular and trying to experiment with some code. However, I seem to be stuck with the app.js file which is throwing an error: Uncaught SyntaxError: Unexpected token . Below is the structure of my application, which I obtained by cloning ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

`Is it time to persist the reducer in redux-persist?`

The redux-persist library offers a way to save the redux state tree in storage and reload it when reopening the app. I understand the importance of restoring the state tree due to its valuable data, but I am puzzled by the concept of persisting reducers w ...

After completing the mapSeries operation, I aim to re-implement the function

How can I return queries (functions) after performing mapSeries? Any help is appreciated! async querys(querys) { const pool = await poolPromise; if (pool != null) { const transaction = new sql.Transaction(pool); ...

Does MongoDB have an equivalent to prepared statements in PHP for enhancing security measures?

As I delve into learning mongodb, a pressing question arises. Does mongodb have security features similar to those found in PHP? In PHP, one could utilize the following code: $stmt = $this->conn->prepare("UPDATE news SET shown = shown+1 WHERE ne ...

Utilize Node.js to encrypt data from an extensive file

Hello, this is my initial inquiry. English isn't my native language and I need some help. I have a large file with about 800K lines that I need to read and encrypt using the sjcl library. So far, I've only managed to write the following code snip ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

Limiting the number of checkboxes selected in a Checkbox Group based on

I am working on a checkboxGroupInput that has 4 options (denoted as A, B, C, D). My goal is to restrict the selection to only 2 choices. The user should be able to pick a 3rd option. In this scenario, only the newly selected (3rd) and previously selec ...