简体   繁体   中英

using setState to add a object in nested array

I'm using ireact set state and trying to post data to my object that is nested with arrays.

 const [data, setData] = useState({
    working_hours: [
      {
        id: '',
        description: '',
        hours: '',
        price: '',
        total: '',
      },
    ],
    parts: [
      {
        id: '',
        description: '',
        unit: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
    other: [
      {
        id: '',
        description: '',
        quanity: '',
        price: '',
        total: '',
      },
    ],
  });

You're not far off, but you need to copy both the outer object and the array you're pushing to. It's also important to use the callback form because you're updating state based on existing state, so you want to be sure you have the most up-to-date state:

const handleAdd = () => {
    setData(data => {
        const test = {
            id: 3,
            description: 'This is a description',
            hours: 4.2,
            price: 500,
            total: 4421,
        };
        return {
            ...data,
            working_hours: [...data.working_hours, test]
        };
    });
};

Let us see how your code is working. You have an object which has three attributes working_hours<\/code> , parts<\/code> and others<\/code> (which are all arrays).

, what is happening behind the scene is, first you copy all the attributes of data<\/code> into a new object, then the attribute working_hours<\/code> is replaced by test<\/code> .

This is how you do it setData({...data, working_hours:[...data.working_hours, test])<\/code>

Then a new array is made, which has all the elements of data.working_hours<\/code> (previous state's working_hours<\/code> ) and test<\/code> . This array is assigned to working_hours<\/code> attribute of the new object, and finally this state is assigned to the new object<\/code> .

This should work

const handleAdd = () => {
    const test = {
      id: 3,
      description: 'This is a description',
      hours: 4.2,
      price: 500,
      total: 4421,
    };
    const newData = {
      ...data,
      working_hours: [
        ...(data?.working_hours ? data.working_hours : {}),
        test
      ]
    };
    setData(newData);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM