Home > front end >  How to update state of object
How to update state of object

Time:08-01

I created front-end for json and now I want to create CMS to add new things to database. My problem start with update state because something not work proper.

 const [object, setObject] = useState([{ name: "",
    Description: "",
price: {
     A: "",
     B: "",
     C: "", }}])

  const changeIloscSztuk = (event, index) => {
                const { name, value } = e.target;

                const tempProducts = object.map((el, i) => {
                  if(i === index) {
                      return {
                      ...el,
                      [name]: value
                    };
                }
                  return el;
                });
                setObject(tempProducts)
              }
   
        const handleChange = (e, index) => {
            const { name, value } = e.target;

            const tempProducts = object.map((el, i) => {
                if(i === index) {
                    return {
                    ...el,
                
                    [name]: value
                    
                  };
              }
                return el;
              });
            setObject(tempProducts);
        };
    
return (
  <>
<Container style={{backgroundColor: "black", color: "white"}}>
    {object.map((name,i)=>{
        return(<>
        {name.name} 
        </>)
    })}
    </Container>


 <form onSubmit={setDodatkowe} ref={formData}>
Dodaj nowy moduł
   
  
<input type="submit" value="dodaj" />
</form>
{object.length>0 ? 
<form ref={formData}>
<Table          responsive  striped bordered hover >
<thead><tr><td>Nazwa usługi</td><td>usun</td></tr></thead>
<tbody>
{object.map((props, index) => (
<React.Fragment key={index}>
    <tr>
   <tr>
  <td>Nazwa <input type="text" className="Nazwa" name="name"   onChange={handleChange}    /> </td>
  <td> Opis<input type="text" className="Description" name="Description"    onChange={handleChange}/> </td>
  <td>Wielkość <input type="text" className="Wielkosc" name="Wielkosc"   onChange={handleChange}/> </td></tr>

</React.Fragment>

  ))}
</tbody>
</Table>
</form>  : ""}
</Container>

after click "dodaj" I see lots of inputs so it is correct. But when I write in field "name" something the state is not updating. Without this step building database is not possible.

CodePudding user response:

The reason for that is that state variables in React are immutable. You cannot simply do object.description = "something". If you insist on having one big nested object, you need to make a copy of the entire object whenever a single property changes.

A common way to do so is

const newObject = JSON.parse(JSON.stringify(object);
// make modifications, for example:
newObject.Description = "something";
setObject(newObject);

CodePudding user response:

React UseStates are immutable. Bit of a pain, but you can use Immer to get rid of this.

npm i immer

Example of immer:

import produce from "immer"

const nextState = produce(baseState, draft => {
    draft[1].done = true
    draft.push({title: "Tweet about it"})
    //draft is muttable
})

  • Related