Puja Dhinchak
Puja Dhinchak

Reputation: 25

setState updates component one state late

In the following code , the name(or any other object /not only string) only gets updated in the component after 2nd change .In 3rd change , it gets the 2nd change value and so on i.e. state is one step behind .

state is one step behind

const [state,setState]=useState([]);

const onChange=(id)={
let vname="hello world";
const temp = state.map((item,i)=>{
if(i===id){
return vname;
}
return item;
});
setState(temp);
}

Upvotes: 2

Views: 296

Answers (1)

Tolumide
Tolumide

Reputation: 994

First, that code looks a bit incorrect: the onChange event should get the event parsed to it.

try something like this:

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const [name, setName] = useState("");
  const [reg, setReg] = useState(["dog", "cat", "monkey"]);
  const [pujab, setPujab] = useState("");
  return (
    <div>
      <label htmlFor="name">firstName:</label>
      <input
        name="name"
        type="text"
        value={name}
        onChange={e => {
          const newFirstName = e.target.value;
          setName(newFirstName);
        }}
      />

      <div />

      <label htmlFor="play">ChangeList: </label>
      <input
        name="play"
        type="text"
        value={pujab}
        onChange={e => {
          const newPujab = e.target.value;
          setPujab(newPujab);
          console.log("iniitiitit");
          for (let i = 0; i < reg.length; i++) {
            if (reg[i] === e.target.value) {
              console.log("yessss");
              reg[i] = "welcome";
            }
          }
        }}
      />
      <p>Animal List: {reg.map(item => item + " ")}</p>
      <p>Changes: {name}</p>
      <p>Names: {pujab}</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I have it on codesandbox here: https://codesandbox.io/s/amazing-hodgkin-7x9nn

Upvotes: 3

Related Questions