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

77
Views
Set state value using string path key from deeply nested object

I am trying to change a deeply nested value within an object using a string path of the key to access the object.

Setup:

const [payload, setPayload] = useState({
    name: "test",
    download: true,
    downloadConfiguration: {
      product: {
        initialDownloadLength: 3,

      }}})

When object value is changed:

  const handleChange = (prop: any) => (e: React.ChangeEvent<HTMLInputElement>) => {

    if (typeof e.target.value === "number") {
      setPayload({ ...payload, [prop]: parseInt(e.target.value) });
    }

    if (typeof e.target.value === "string") {
      setPayload({ ...payload, [prop]: e.target.value });
    }
  };

When I change values in the outermost layer of the object it works fine and updates the value e.g.

onChange={handleChange("name")}

but I am unable to access the initialDownloadLength key that is nested within product and downloadConfiguration. I have tried "downloadConfiguration.product.initalDownloadLength" and using square brackets etc, but each time it creates a new object at the top most layer of the object.

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

0

You can use the solution in here dynamically-set-property-of-nested-object in your handleChange method like this:

// set method copied from the above link
function set(obj, path, value) {
    var schema = obj; 
    var pList = path.split('.');
    var len = pList.length;
    for(var i = 0; i < len-1; i++) {
        var elem = pList[i];
        if( !schema[elem] ) schema[elem] = {}
        schema = schema[elem];
    }
    schema[pList[len-1]] = value;
}
...

const handleChange = (prop) => (e) => {
  let value;
  if (typeof e.target.value === "number") {
    value = parseInt(e.target.value);
  }

  if (typeof e.target.value === "string") {
    value = e.target.value;
  }

  setPayload((prevState) => { 
     const newState = {...prevState};
     set(newState, prop, value);
     return newState;
 })
};
....

onChange={handleChange("downloadConfiguration.product.initialDownloadLength")}
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!