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

I'm encountering some puzzling errors from the Codacy feature in GitHub that are leaving me completely baffled

I'm currently using Codacy in my code repository to assess the quality of my work. Struggling with two errors during commit, unsure how to troubleshoot them. Can anyone offer assistance? Issue: Expected property shorthand. Error occurs in this line ...

Guide on automatically removing a DOM element in Jquery after a set amount of time

Is there a way to delete an HTML element after a specific period of time? If a certain condition is met before the allotted time, I want to pause the timer from deleting the element. Here's a snippet of code for reference: <ul> <li dat ...

Experiencing an "isTrusted" error while working with the GLTFLoader

QUERY: All was running smoothly: I successfully transformed my FBX files to GLTF in the /GLTF/ directory. Unfortunately, after noticing missing geometry in some converted files, I attempted another conversion of the FBX files, this time to /TEST/. Unexp ...

"Encountering a 404 error during deployment with ExpressJS and React

My project functions correctly when run locally. To start it locally, I use the command npm run start in both the project root and client root simultaneously. I am currently developing a basic application with Express and Create React App. After successfu ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

Is there a way to customize the CSS ul menu specifically for the JavaScript autocomplete feature?

I have created a search page with autocomplete for the first textbox, but I noticed that the ul/li CSS classes used for styling the main menu are impacting the JavaScript list. How can I override the menu styling to display a regular list format? Being a ...

Use the jQuery .GET() method two times to retrieve data and obtain the outcomes

My code involves making a series of GET calls where the returned data from one call is used in another call before returning the final results. However, I want to ensure that my program waits until all the data is retrieved. This is what I have come up wi ...

Getting an array of all visible text on a page using the same locator in Selenium

Within different sections of the webpage, I have utilized the following locator (excerpt from HTML): <table id="userPlaylistTable" cellspacing="0" cellpadding="0"> <p class="title"> ABC </p> <p class="title"> DEF </p> ...

Tips for positioning a hero image perfectly using HTML and CSS

I am looking to display two hero images on the index page and wondering how to align them. My goal is to have both images centered with 50px separation under the header, ensuring they are of equal height. Will using the flex property work for hero images? ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

What is the best way to display cards next to each other on desktop and mobile devices while maximizing available space?

In the world of React components, there exists a card representation within a grid view that adapts based on available screen space; function EngineerCard(engineer: EngineerDetail) { return ( <div className='engineerCard'> <d ...

Instructions for implementing this script in HTML and JavaScript: utilize the clone() function

I came across this code snippet here function displaytickets(){ var $panel = $('<div/>').addClass('col-xs-3 panel panel-default') $panel.append($('<div><h3 class="panel-title">Title</h3></div>&a ...

BASH-SHELL SCRIPT: Display a specific portion of content from a file

Recently, I stumbled upon a text file containing a snippet of HTML code: >>nano wynik.txt which includes the following text: 1743: < a href="/currencies/lisk/#markets" class="price" data-usd="24.6933" data-btc= "0.00146882" My goal is to extr ...

Tips for placing a form Dialog in Material UI

I have designed a basic form using https://material-ui.com/ My form consists of two fields: https://i.stack.imgur.com/acGVH.jpg I have included a form Dialog popup that appears when the user clicks on the "Booking name" field. The issue is that my Dial ...

How can I implement user account functionality with only JavaScript in an Angular frontend and Node.js/Express server?

Many resources I've come across utilize php or a similar language. With an Angular frontend and Node/express server code in place, but no backend yet, I'm uncertain about how to approach user sign-up. ...

jQuery AJAX chained together using promises

In my current project, I am facing an issue where I have 4 get requests being fired simultaneously. Due to using fade effects and the asynchronous nature of these requests, there are times when empty data is received intermittently. To address this issue, ...

Can I access my account through web3React?

Programming: const App = () => { const { account } = useWeb3React() return ( {account ? <Dasboard/> : <HomePage/> } ) } Challenge: The delay in loading the account causes a flicker on the interface as the HomePa ...

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...

Exploring Material-UI in React: A guide to integrating and utilizing breadcrumbs

Can breadcrumbs be integrated using material-ui in a reactjs-based setup? If so, how can I go about implementing them? ...