Obsolete state in useIonViewWillEnter

I have a problem with data coming from React Context being stale inside of useIonViewWillEnter hook.

Example quasi-code:

export function CustomerForm(): JSX.Element {
  /* STATE comes from Context provider */
  const {customers, set_customers} = useContext(AppContext);
  console.log('CustomerForm render', customers[0])

  useIonViewWillEnter(() => {
    const customerOne = customers[0]
    fn_that_programmatically_populates_form_fields(customerOne)
    console.log('useIonViewWillEnter', customers[0])
  });

  return (
    <form-that-uses-customer-data>
      {customers[0]}
      <button 
        onClick={(customerDataFromThisForm) => {
          // When User updates customer data in the form - new data is saved via set_customers to Context.
          const updatedCustomers = [...customers];
          customers[0] = customerDataFromThisForm;
          set_customers(customers)
        }
      >Save customer</button>
    </form-that-uses-customer-data>
  );
};

type Customer = {name: string}

I have two screens: CustomerForm and CustomerList.
My course of action:

  • Enter CustomerForm; let’s say, initial customerOne name is Jane; console will log:
    CustomerForm render, {name: "Jane"}
    useIonViewWillEnter, {name: "Jane"}
  • Change the name to Kate and click Save customer
  • Return to CustomerList
  • Hit the first customer in the list
  • CustomerForm will be shown; console will log:
    useIonViewWillEnter, {name: "Jane"}

What’s the prob with useIonViewWillEnter??

2 Likes

maybe not helping with this problem and I am not a react person, but why do you use function in the beginning and fat arrow for useIonViewWillEnter. Isn’t the function keyword creating things you dont want?

Both of these fn declarations are valid and do not impact the runtime effects

1 Like

Ok. The solution is to add customers to dependencies list - the second arg to useIonViewWillEnter

  useIonViewWillEnter(() => {
    const customerOne = customers[0]
    fn_that_programmatically_populates_form_fields(customerOne)
    console.log('useIonViewWillEnter', customers[0])
  }, **[customers]**);

Which is NOT documented

3 Likes

Hey thanks for pointing this out. Can you open an issue on the ionic-docs repo for this? We should add a note about this.

already
although that repo seems to be rarely maintained: there are dozens of pull requests & un-addressed issues

1 Like

The docs are maintained…

Most of the pull requests are either related to deps or out of date/incorrect

Since May I’ve opened 9 issues. Only one has been addressed…