'How can update a object state in inputs ? (React js Hooks)
I'm new in React and I saw a lot of topics about updateo bject state but in my case I continue with erros.
I have a object useSate and I want update every time my input changes. I have tried the spread operator.
My state :
const [inputs, setInputs] = useState({
topic: {
coins: 0,
money: 0,
cash: 0,
}
})
my handle funtion :
const handleMoney = (e) => {
setInputs(prevState =>({
inputs:{
...prevState.inputs,
coins: e.target.value
}
}))
}
And my form ( is from react boostrap):
<Form.Control
min={0}
type="number"
value={inputs.coins}
onChange={handleMoney }
/>
Solution 1:[1]
const handleMoney = (e) => {
setInputs({
...inputs,
inputs['topic']['coin'] = e.target.value
})
Otherwise You can use
const handleMoney = (e) => {
const newInput = {...inputs}
newInput['topic']['coin'] =e.target.value
setInputs(newInput)
})
And form is
<Form.Control
min={0}
type="number"
value={inputs.topic?.coins}
onChange={()=>handleMoney() }
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Khandker Ashik Mahmud |
