Skip to content

Keep form values persistent

Norbert Schuler edited this page Dec 12, 2020 · 1 revision

Case - So there are some cases where we should persist the value of the form when we move from one page to another.

For example - After adding gift details in the first page of donation, we move to the next screen and we might want to come back again. Since react will re-render the components all the form inputs will be lost and user will have to type it again. (We still have the data, only the form inputs are lost)

Solution - React Hook forms has a function called reset . Using this you can reset the form fields with whatever values you will provide. For this to work, all the fields must be registered using the register function and have a name field. With that now I can pass an object to reset the form fields with default values -

const defaultDetails = {
        recipientName:giftDetails.recipientName,
        email:giftDetails.email,
        giftMessage:giftDetails.giftMessage
      }
reset(defaultDetails)
Clone this wiki locally