-1

This is a follow up question to this question:

Why calling react setState method doesn't mutate the state immediately?

I got a React component with a form which can be used to add items or edit a current item. The form is being saved as a state of the component along with all its values.

When submitting the form I'm doing this:

const onSubmitForm = () =>
{
      if(editedItem) //the item to edit
      {
        EditSelectedItem();
        setEditedItem(undefined);
      }
      else
      {
        //handle new item addition
      }
      clearFormValues();
      setEditedItem(undefined);
  }

And the edit method:

const EditSelectedItem = () => 
{
    setItemsList(prevItemsList => 
      {
        return prevItemsList.map(item=> 
          {
            if(item.id !== editedItem.id)
            {
              return item;
            }
            item.name = formSettings["name"].value ?? "";
            item.description = formSettings["description"].value ?? "";
            item.modified = getNowDate();
            return item;
          });
      })
  }

The problem is that because the setItemsList is not being called synchronously, the clearFormValues(); in the submit form method is being called before, and I lose the form's old values (in formSettings)..

How can I keep the old values of formSettings when the setItemsList is called?

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203

1 Answers1

0

The solution is easy here, you can store the formValues in an object before using it an setItemsList

const EditSelectedItem = () => 
{

    const values = {
      name: formSettings["name"].value ?? "";      
      description: formSettings["description"].value ?? "";
      modified: getNowDate();
   }
    setItemsList(prevItemsList => 
      {
        return prevItemsList.map(item=> 
          {
            if(item.id !== editedItem.id)
            {
              return item;
            }

            return {...item, ...values};
          });
      })
  }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Interesting, those values should not have been cleared. But I am glad you were able to work around the above solution yourself :-) – Shubham Khatri May 26 '20 at 10:23
  • 1
    I deleted the comment since what you wrote is correct, but my items here are classes and not just simple objects – CodeMonkey May 26 '20 at 10:23