Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
React: How to save previous states in a object with dynamic properties?

I'm trying to store some information every time that a change occurs on the value of a input element.

const [inputs, setInputs] = useState({})

const addInput = (name, value, type) => {
    setInputs(() => {
      inputs[name] = {
        "value": value,
        "type": type
      }
      return inputs
    })
  }

...

  const handleInput = (event) => {
    addInput(props.name, event.target.value, event.target.type)
    ...
  }

I've got an empty object callled inputs, and if the user types inside an input like this:

<input name="username" value={onChange} type="text">

the inputs object should have now a property called username:

{
  username: {
    type: "text",
    value: : "text-from-the-user",
  }
}

but my problem is: When I add two inputs or more inside this inputs object, a override occurs in all the properties that isn't having a change.

For example: If I have two objects inside the inputs...:

{
  username: {
    type: "text",
    value: : "John",
  },
  email: {
    type: "email",
    value: : undefined,
  },
}

...and I add some text in the email input, the inputs object loses the data from the username object:

{
  username: {
    type: undefined,
    value: : undefined,
  },
  email: {
    type: "email",
    value: : "Jhon123@yahoo.com",
  },
}

So I'm trying to implement the ...prev inside this setInput, but I'm having trouble with this, because inside this setInput I say that I want to create new objects if they don't exist:

...
      inputs[name] = {
        "value": value,
        "type": type
      }
...
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should do it like this:

setInputs((ps) => ({
    ...ps,
    [name]: {
        "value": value,
        "type": type
    }
}))

When you set state:

  • you must update state in immutable way
  • and useState overwrites new value over the old one (doesn't merge like it was in class components)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!