Controlling various states within React can be a challenging task to

Currently tackling a challenge within a tennis application as I struggle with managing numerous states. To elaborate, the first round of a tennis tournament involves 128 players where each row consists of a player and their seed.

https://i.stack.imgur.com/VDWJa.png https://i.stack.imgur.com/KYk6F.png

Array.from(Array(128)).map((p, index) => {

const oddIndex = index * 2 + 1
  const evenIndex = index * 2 + 2

  const getCurrentSeed = (position) => {
    const seed = !objectIsEmpty(games) && games?.rounds[round.round]?.positions[position]?.seed

    return seed || ''
  }

  const getCurrentATPPlayer = (position) => {
    const ATPPlayer = !objectIsEmpty(games) && games?.rounds[round.round]?.positions[position]?.atp_player
    return ATPPlayer || {}
  }

<div className="player">
 <ATPPlayerFinderWrapper position={oddIndex} setATPPlayerId={setATPPlayerId} setCurrentPosition={setCurrentPosition} ATPPlayer={getCurrentATPPlayer(oddIndex)} />
</div>
<div className="seed">
    <TextField
      id={`seed${oddIndex}`}
      label="Seed"
      variant="standard"
      onChange={(e) => setSeed(e.target.value)}
      InputProps={{ disableUnderline: true }}
      value={getCurrentSeed(oddIndex)}
   />
</div>

});

Facing a major setback when encountering rows from the back end where numerous states are required for each textfield but unfortunately, it's not functioning as expected and poses a significant issue in terms of management.

Answer №1

To address this issue, the suggested approach is to store your array in a state and initialize each of its values as an empty string.

const [seeds, setSeeds] = useState(Array(128).fill(''));
const [ATPPlayers, setATPPlayers] = useState(Array(128).fill({}));

Subsequently, whenever there is a change in the state, update its value accordingly

const handleSeedChange = (position, value) => {
    const newSeeds = [...seeds];
    newSeeds[position] = value;
    setSeeds(newSeeds);
  };

  const handleATPPlayerChange = (position, player) => {
    const newATPPlayers = [...ATPPlayers];
    newATPPlayers[position] = player;
    setATPPlayers(newATPPlayers);
  };

Below is the complete code snippet tailored to resolve your particular problem:

import React, { useState } from 'react';

const TennisBracket = ({ games, round }) => {
  const [seeds, setSeeds] = useState(Array(128).fill(''));
  const [ATPPlayers, setATPPlayers] = useState(Array(128).fill({}));

  const getCurrentSeed = (position) => seeds[position] || '';

  const getCurrentATPPlayer = (position) => ATPPlayers[position] || {};

  const handleSeedChange = (position, value) => {
    const newSeeds = [...seeds];
    newSeeds[position] = value;
    setSeeds(newSeeds);
  };

  const handleATPPlayerChange = (position, player) => {
    const newATPPlayers = [...ATPPlayers];
    newATPPlayers[position] = player;
    setATPPlayers(newATPPlayers);
  };

  return (
    <div>
      {Array.from(Array(128)).map((p, index) => {
        const oddIndex = index * 2 + 1;

        return (
          <div key={index}>
            <div className="player">
              {/* Incorporate your ATPPlayerFinderWrapper or any other relevant component */}
              {/* Assuming it has a mechanism to transmit selected player data to the parent component */}
              <ATPPlayerFinderWrapper
                position={oddIndex}
                setATPPlayerId={setATPPlayerId}
                setCurrentPosition={setCurrentPosition}
                ATPPlayer={getCurrentATPPlayer(oddIndex)}
                onPlayerChange={(player) => handleATPPlayerChange(oddIndex, player)}
              />
            </div>
            <div className="seed">
              <TextField
                id={`seed${oddIndex}`}
                label="Seed"
                variant="standard"
                onChange={(e) => handleSeedChange(oddIndex, e.target.value)}
                InputProps={{ disableUnderline: true }}
                value={getCurrentSeed(oddIndex)}
              />
            </div>
          </div>
        );
      })}
    </div>
  );
};

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

Low scoring performance in Lighthouse on a nearly empty page built with Next.js

While working on my Next.js project locally, I used npm run dev for development. After testing my website, I noticed that it scored a 40 in Performance. https://i.stack.imgur.com/3jmro.png Despite trying to use Lighthouse in secret mode, the results rem ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Switching from HTTP to HTTPS with Express and Heroku

Despite Heroku's suggestion to use NPM packages, I've had no luck finding one that successfully forces SSL for express apps. The only solution that seems to work is the following, but it angers Google. Question: Can anyone provide a reliable met ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

Whenever a button is clicked in a custom column rendering of a React material table, the sorted state is lost. This issue occurs whenever any state update is triggered

I encountered an issue with my code involving a Collapsible list triggered by an Icon Button. After sorting the table and then expanding the list, the table reverts back to its original unsorted state. I am puzzled as to why this is happening. <Material ...

nextjs dynamic routing is not compatible with the next-i18next framework

After integrating next-i18next into my Next.js project using the official guide, everything appeared to be functioning correctly. However, I encountered a 404 error when switching from the default language (Italian) to English and navigating to the detail ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

Using a customHook to dynamically swap images in React

Currently, I am facing an issue with a custom hook that manages the theme (dark/light mode) using tailwind CSS. Specifically, I have two images that are supposed to switch based on the theme mode selected. Despite successfully changing FontAwesome icons fr ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

Struggling to add Material UI to my fresh React project

Recently, I created a new React app with Create React App. However, when I tried to install Material UI, I encountered an error message that is causing some confusion: Link to image of console All my other packages are installing without any issues. Coul ...

How can a server component be rendered conditionally based on the state set in the client component?

Currently, I am working on implementing a tailwinds css template sidebar that updates the main div with components based on the active sidebar tab. To achieve this functionality, I need to utilize state to determine which sidebar tab is currently active. I ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

Solving the issue of duplicate activeClassName in React

I struggle with English, but I am proficient in React js. Currently, I am utilizing activeClassName(), which is causing me some issues. My goal is to structure my website's URL as follows: localhost:3000/icons/ localhost:3000/icons/docs/ loc ...

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Supabase is encountering an issue: 'TypeError: fetch failed'

I'm currently developing a to-do list application using Supabase and NextJS-13. However, when I tried fetching the lists from Supabase, the server returned an error. Error Image The List table on Supabase consists of three columns: id created_ ...

Testing a component with React Testing Library and Jest while passing a boolean value: step-by-step guide

I am currently testing the visibility of the logout link for users who are logged in. The value I pass in the test determines whether the user is logged in or out. The isAuthenticated parameter is a boolean: true means the user is logged in, false means th ...

Leverage the power of Google Maps within your Next JS application

Has anyone encountered the error Unhandled Runtime Error Invariant Violation: useGoogleMap needs a GoogleMap available up in the tree when trying to use useGoogleMap() within a NEXT JS component? I am looking for a way to access the Google Map inside my ...

Experiencing a repetitive occurrence of the error: "SyntaxError: Encountered an invalid or unfore

I've encountered a persistent error when attempting to execute my index.mjs file. Here is the content of my index.mjs file: import WebSocket, { WebSocketServer } from "ws"; import http from "http"; import express from 'express ...

cleaner urls using nextjs routing

Currently working on developing a fresh marketing platform for my company utilizing next.js, and encountering some hurdles with URLs. Essentially, I've created a custom API route to retrieve data from our internal database using Prisma: getAllDealers ...