React: Update a nested property in state

·

1 min read

Method 1: Single object in state

// imports
import React,{ useState } from 'react';

export function MyComponent(){
  // init state
  const [myState,setMyState] = useState({ 
    name: '', 
    age: 0, 
    city: '' 
  });

// optional handler function, setMyState is the required part
  function updateDynamicState(stateKeyToUpdate, newValue){
      // use array deconstruction: [stateKeyToUpdate]
      setMyState({[stateKeyToUpdate]: newValue});
  }

  updateDynamicState('age', 32);
  updateDynamicState('name','John Doe');
}

Method 2: Array of objects in state

// imports
import React,{useState} from 'react'

// init state (array of objects)
const [dogs, setDogs] = useState([
  {id: 1234, name: 'Fido', breed: 'terrier'},
  {id: 5678, name: 'Muffin', breed: 'shitsu'}
])

// Usage
function updateDogNestedAttr(dogId, attrName, updValue){
  const updatedDogs = [...dogs]
  newState.map((thisDog) => {
    if(thisDog.dogId === dogId){
      if(attrName==='name') thisDog.name = updValue
      if(attrName==='breed') thisDog.breed = updValue
    }
  })
  setDogs(updatedDogs)
}

// Call with different attrs
updateDogNestedAttr(1234,'name','Rover')
updateDogNestedAttr(1234,'breed','rottweiler')

Assumptions

  • React 16.8+ (hooks specifically)