Home > Enterprise >  How to store onchange value one by one in array state in react js
How to store onchange value one by one in array state in react js

Time:10-20

I am a new student for react js. I have a text field and I need to store my text field value temporarily because I need to type value in the same text field 3 times .So I created a temp array state to store my onChange value. But there is something wrong with the code. The value stores my temp array, But not the final value. It's store all change value. Like my image. enter image description here

enter image description here

I tried to fix this but I can't. If anyone can help me with this issue, It's really mean to me. Thank you.

  const [category, setCategory] = useState('');
  const [temp, setTemp] = useState([]);


function changeTitle(event) {
    setCategory(event.target.value);
   setTemp((temp)=>[...temp, category])
}

<TextField
  value={category}
  label="Name"
   onChange={changeTitle}
 />


<Button
   onClick={testFinalValue}
  >
   Next
</Button>

CodePudding user response:

The problem is the "category" in your function changeTitle still holds the old value, so you need to use "event.target.value" instead of "category" to get the final value:

function changeTitle(event) {
   setCategory(event.target.value);
   setTemp((temp)=>[...temp, event.target.value])
}

CodePudding user response:

Your issue is in the onChange TextField1 component, in the onChange you need to do it like this:

<TextField
  value={category}
  label="Name"
   onChange={(event) => changeTitle(event)}
 />

If you want to use it without the event function in the onChange internally react use the short name e in your changeTitle function like this:

const [category, setCategory] = useState('');
  const [temp, setTemp] = useState([]);


function changeTitle(e) {
    setCategory(e.target.value);
   setTemp((temp)=>[...temp, category])
}

<TextField
  value={category}
  label="Name"
   onChange={changeTitle}
 />


<Button
   onClick={testFinalValue}
  >
   Next
</Button>

CodePudding user response:

try using useEffect hook maybe solve your problem but I'm not sure useEffect(()=>{ const oldTemp=[...temp] const newTemp=[...temp,category] setTemp(newTemp)

},[category])

  • Related