简体   繁体   中英

Usestate + Setstate [TypeError: Invalid attempt to spread non-iterable instance.] - React Native Form Handling

I am trying to update the state by adding a new object called "billing". My initial state looks like this:

const [data, setData] = useState({
    payment_method: 'bacs',
    payment_method_title: 'Direct Bank Transfer',
    set_paid: true,
    line_items: [
      {
        product_id: 93,
        quantity: 2,
      },
    ],
  });

After I add the form data I want it to look like this:

const [data, setData] = useState({
    payment_method: 'bacs',
    payment_method_title: 'Direct Bank Transfer',
    set_paid: true,
    line_items: [
      {
        product_id: 93,
        quantity: 2,
      },
      {
        product_id: 22,
        variation_id: 23,
        quantity: 1,
      },
    ],
    shipping_lines: [
      {
        method_id: 'flat_rate',
        method_title: 'Flat Rate',
        total: 10,
      },
    ],
 billing: {
        first_name: "John",
        last_name: "Doe",
      },
  });

However when I run this function I get a typeError saying I can not spread the state. Billing contains the data from Formik in an object that looks like this {"first_name": "", "last_name": ""} :

  const addData = (billing) => {
    setData((currentData) => {
      return [billing, ...currentData];
    });
  };

How do I either restructure my state array or spread the currentState so that I can add my billing object.

Yout state data is an object not an array, this is the reason [billing, ...currentData] fails.

You need to set it like this instead:

const addData = (billing) => {
  setData((currentData) => {
    return { billing, ...currentData };  // <<< spread inside an object
  });
};

You are trying to spread an object into an array, hence the error. Make sure you have {} not [] in your state, and you can clean it further as below:

const addData = (billing) => setData((currentData) => {billing, ...currentData});

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