Update state in object inside other object, React js

167 Views Asked by At

well, i have an object inside another object, and i want to update the state in one property or more in the second object, this is the state :

const [products, setProducts] = useState({
  name: '',
  type: '',
  price: '',
  sizes: { s: false, m: false, l: false, xl: false }
});

how can i access a property in the second object i've tried this but it's not working :

setProducts({...products, sizes : {...sizes, sizes[m] : true}}) // this not working

is there any way to do this ?

3

There are 3 best solutions below

0
On BEST ANSWER

Try this one.

setProducts({ ...products, sizes: { ...products.sizes, m: true } });
0
On

If you want to update additional sizes with either true or false you could abstract that into

const updateSize = (field, value) => {
  setProducts(prevState=> ({ 
    ...prevState,
    sizes: { ...prevState.sizes, [field]: value }
  }));
}
0
On

You can try:

setProducts(prevState=> ({ ...prevState, sizes: { ...prevState.sizes, m: true } }));

this will also prevent issues in case of closure