0

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 }
           />

2 Answers 2

2

Here is code click to see .If its help please mark as answer

  const [state, setState] = useState({
    toggle: false,
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
  });

  const onHandleChange = (e) => {
    const { name, value } = e.target;
    setState(pre => ({
      ...pre,
      topic: {
        ...pre.topic,
        [name]: value
      }
    }))
  }

  return (
    <div className="App">
      <p>Coins : {state.topic.coins} </p>
      <p>Money : {state.topic.money} </p>
      <p>Cash : {state.topic.cash} </p>
      <input type="number" name='coins' onChange={onHandleChange} value={state.topic.coins} />
      <input type="number" name='money' onChange={onHandleChange} value={state.topic.money} />
      <input type="number" name='cash' onChange={onHandleChange} value={state.topic.cash} />
    </div>
  );
Sign up to request clarification or add additional context in comments.

1 Comment

If it's helpful for you please mark it as an answer.
0
 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() }
       />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.