State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected.

Essentially, entriesNum receives a number as an event and changes the order of the initUsers state value based on that number:

Enter Image J Here

to this :

enter image description here

const [iteratedUsers, setIteratedUsers] = useState([...users]);
const [Newobj, setNewobj] = useState([]);
const [isNewObj, setIsNewObj] = useState(false);
const [initUsers, setUsers] = useState(users);`
const entriesNum = (event) => {
  const newi = Math.ceil(5 / event.target.value);

   for (let i = 0; i < newi; i++) {
    if (iteratedUsers.length >= event.target.value) {
      Newobj.push(
        iteratedUsers.splice(0, event.target.value).reduce((obj, key, i) => {
          obj[i] = key;
          return obj;
        }, {})
      );
    } else {
      Newobj.push(
        iteratedUsers.splice(0).reduce((obj, key, i) => {
          obj[i] = key;
          return obj;
        }, {})
      );
    }
  }
     
  setNewobj([]);
  setIsNewObj(true);
  setUsers(Newobj);
    
  setIteratedUsers(users);  
};

Due to having two forms of initUsers, I had to set up two ways of destructuring like this:

{isNewObj ?
  initUsers.map((objUser ) => (
    < >
      {Object.keys(objUser).map((numo) => (
        <div
          key={numo}
          className="contacts-info  border-solid border-2 border-black table-row w-full "
        >
          <input type={"checkbox"} className={`${shortcut}`} />
          <div className={`${shortcut}`}>
            {objUser[numo].index}
          </div>
          <div className={`${shortcut}`}>
            {objUser[numo].email}
          </div>
          <div className={`${shortcut}`}>
            {objUser[numo].access}
          </div>
        </div>
      ))}
    </ >
  )) :
  initUsers.map(({ index, handle, phone, email, access }) => (
    <div
      key={id}
      className="contacts-info  border-solid border-2 border-black table-row w-full "
    >
      <input type={"checkbox"} className={`${shortcut}`} />
      <div className={`${shortcut}`}>{index}</div>
      <div className={`${shortcut}`}>{handle}</div>
      <div className={`${shortcut}`}>{phone}</div>
      <div className={`${shortcut}`}>{email}</div>
      <div className={`${shortcut}`}>{access}</div>
    </div>
  ))
}

The second condition destructures the initUsers when it is not nested and shows the following result:

enter image description here

The first one destructures it in its nested form and shows the following result:

enter image description here

Instead of getting 5 rows, the result of destructuring the nested initUsers gives me 9.

Answer №1

To update the state in ReactJs, you should avoid using Newobj.push as it does not work with ReactJs state management. Instead, you can use setNewobj to set your new data.

Another way to update the state is by using setNewobj((prev) => [...prev,{}]). Here, prev represents the old data that you currently have.

Answer №2

React state remains constant, making direct modifications impossible.

When attempting to alter Newobj, opt for setNewobj([...Newobj]) as opposed to Newobj.push.

Once Newobj has been adjusted, execute setUsers(Newobj) followed by setNewobj([]);

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

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...

Stop Ajax from activating jQuery function

Upon examining our Drupal site, we discovered a straightforward jQuery script that inserts a div class containing content: (function($) { Drupal.behaviors.myHelpText = { attach: function (context, settings) { //code begins //adjusting placeholder ...

Having trouble submitting a form with React and Formik

Here is the Model (popup) code I am using to send the user's email address to the backend service. The Model component is being rendered in my Login Component. However, I am facing an issue where I am unable to submit this form. Despite having working ...

The issue of the footer kicking out of place in the HTML layout was successfully resolved after

I am in the process of creating a simple footer that will always stay at the bottom of the page. The content on the page will not exceed the screen size, eliminating the need for scrolling. (There are a total of 5 HTML pages, and I want the footer and head ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

Having issues with Attributes.Add() function on ASP.NET platform

After adding CSS through code behind in asp.net on page_load, it works perfectly on my local environment but fails to work on the server. Here is the code snippet for your reference: protected void Page_Load(object sender, EventArgs e) { string selec ...

Scanner (IE5) impact on page load speeds

I have developed an MVC project which is designed as a single-page application (SPA) utilizing knockoutjs and sammy frameworks. The following script is placed in the head section of the page: <script> var startTime = (new Date()).getTime(); </ ...

Utilizing a Nodemailer template with a JSX/React component: A step-by-step guide

Currently utilizing Next.js with Nodemailer, my goal is to incorporate React / JSX components as templates in Nodemailer. In my current setup for Nodemailer, I have to manually write the HTML template like this: html: ` <div style="h ...

Embed HTML code to a website using a PHP script on a separate webpage

As a newcomer to PHP, I may have a silly question. Let's say I have a form: <form id="createNewGallery" name="newgallery" method="GET" action="code.php"><p><strong>please choose the number of pictures you want to upload: </str ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Creating a schedule by aligning each day of the week with its corresponding date

weekly calendar<----img here--! I am looking to enhance my weekly table by incorporating a calendar system into it. Instead of just displaying the year in the image, I want it to showcase a 7-day week layout (for example: 12/20/20 - 12/27/2020), with ...

What causes certain CSS properties to scroll while others remain fixed?

I am experiencing a strange issue with my table. I am utilizing the tableHeadFixer jQuery plugin to create a fixed header with a scrollable table body. In my CSS, I have a class called table which is defined as follows: .table thead { color: blue; ...

Steps to successfully click a button once the popup window has finished loading entirely

Is there a way to programmatically click on an HTML element? I am currently using JQuery selectors to identify a button and then trigger a click event. $('span.firstBtn').click(); Once this button is clicked, a popup window appears. How can I w ...

Unexpected behavior from Jquery

Users can select options that reveal more choices and text boxes upon clicking. Despite copying and pasting the code for all options, one specific part is not working as expected. The rest of the options function correctly. The code snippet causing issue ...

Assess the HTML containing v-html injection

Is there a way to inject raw HTML using Vue, especially when the HTML contains Vue markup that needs to be evaluated? Consider the following example where HTML is rendered from a variable: <p v-html="markup"></p> { computed: { m ...

Removing a jQuery class while simultaneously adding it to different elements

I am currently working on a webpage where I have a row of 6 images. The first image, when the page loads, undergoes transformations using CSS3 due to a specific class applied to it. When the user hovers over the other images in the line, the same class is ...

Troubleshooting JWT Session Errors in Next Auth / NextJS

Hello, I am in need of assistance with the authentication process using the getServerSession method of next-auth. I am utilizing the magic link login with the prism adapter. The frontend session seems to be working fine and the sessions are correctly stor ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...