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

124
Views
I am trying to add elements to object using usestate in React?

I am trying to add a new fields in the useState hook

// prevstate  
let [currentdata, setcurrentdata] = useState({
   id:'',
   name:''
  })

I try to add new fields in the object like that

   setcurrentdata(currentdata => ({
            ...currentdata,
            q: quantity,
          }))

but it did not add new fields

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The code snippet below may be one possible solution to achieve the desired objective.

NOTE: I personally dislike the idea of using useState in conjunction with such objects & prefer multiple simpler useState on each variable instead.

Code Snippet

const {useState} = React;

const MyFunction = () => {
  const [badStateObj, setBadStateObj] = useState({
    id: '',
    name: ''
  });
  const clickHandler = (propName) => setBadStateObj(prev => ({
    ...prev,
    [propName]: prev[propName] || ''
  }));
  const updateHandler = (propName, propVal) => setBadStateObj(prev => ({
    ...prev,
    [propName]: propVal
  }));
  
  return (
    <div>
      {Object.entries(badStateObj).map(([k,v]) => (
        <div>
          Key: {k} &emsp; Value: {v} &emsp; &emsp;
          <button
            onClick={() => updateHandler(k, prompt(
              `Enter new value for ${k}`
            ))}
          >
            Update {k}
          </button>
        </div>
      ))}
      <button
        onClick={() => clickHandler(prompt('Enter prop name'))}
      >
        Add new prop
      </button>
    </div>
  );
};

ReactDOM.render(
  <div>
    <h4>Demo showing the useState that I personally dislike</h4>
    <MyFunction />
  </div>,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

Explanation

  • The badStateObj is initialized with only id and name props
  • When user clicks the Add new prop button, a new prop may be added
  • Separate buttons exist to update the value of each individual prop
  • clickHandler adds the new prop entered by user with '' value.
  • updateHandler accepts propName and propVal as parameters and updates the appropriate props within the badStateObj.
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!