Joe
Joe

Reputation: 122

Get value from e.target.name and use in react hooks setState

The name on a input is the same as a prop in my state (React hooks) so I tried doing this, but it dosen´t work:

setState({ ...state, hasChanged: true, [e.target.name]: e.target.value });

When I´m doing it like this it works:

state[e.target.name] = e.target.value;

I know that´s not the proper way to do it but how do I set it in setState instead? I know I have done a simulera thing before but can´t remember how I did.

EDIT:

Thanks for all the answers.

I found a part of the problem, the state was also updated by another function so that function overwrites what I tried to update in this function. I´m now trying to solve that first...

Upvotes: 2

Views: 6709

Answers (2)

xtr
xtr

Reputation: 143

All I can tell you is that the first method creates a new object with new values, the second method just alters the object. If you are passing down the object (state) and then you assign a new object, without propagating that change upwards the reference to the object stays unchanged in the calling context and therefore might not reflect the changes e.g

function Component1(){
   const[state,setState] = useState({})
   return <Component2 state={state}></Component2>
}

function Component2(){
  const[state, setState] = useState(props.state)

  //this creats a new objects Comoponent1 wont "see the changes", state references 
  // a different object in Component1 and Component2
  setState({...state, changed: true}; 


  //this alters the object Component1 passed, Component1 and Component2 will keep 
  //the same reference
  state[changed] = true 
}

Your question isn't very specific but this could likely be the source of your problem.

Upvotes: 0

Rob Terrell
Rob Terrell

Reputation: 2562

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [formData, setFormData] = useState({ answer1: "" });

  const handleChange = ({ target: { name, value } }) => {
    setFormData({ ...formData, hasChanged: true, [name]: value });
  };

  console.log(formData);

  return (
    <div className="App">
      <input name="answer1" value={formData.answer1} onChange={handleChange} />
    </div>
  );
}

you will need the name prop on your inputs for this to work

here is a code pen, https://codesandbox.io/s/admiring-dream-qzzhi?file=/src/App.js I'm not very clear on what you're attempting to do because you didn't provide very much context but this seems to get the job done

Upvotes: 3

Related Questions