Advanced topics
Form Context

Form context

Use the LetsForm context property to store volatile values to be used in Form Scripts without updating the Form Schema (i.e. access tokens, etc)

For example consider the example of the Select component

const MY_FORM = {
  component: 'select',
  label: 'Country',
  name: 'country',
  options: [
    { value: 'us', label: 'United States' },
    { value: 'it', label: 'Italy' },
    { value: 'gr', label: 'Greece' }
  ],
  script: `
    const res = await fetch('some_url?country=' + value, {
      headers: {
        'Authorization': 'Bearer ' + context('token')
      }
    });
    const stateOptions = await res.json();
    setValue('state', 'options', stateOptions);
  `
},
{
  component: 'select',
  label: 'State',
  name: 'state',
  options: []
}

in this use case when the country component is selected, it triggers an HTTP call to get the options for the state dropdown using an access token stored in the context property

const MyView = () => {
  const [formContext, setFormContext] = useState({
    token: 'my-token'
  });
 
  return (
    <LetsForm
      form={MY_FORM}
      context={formContext}
    />
  );
};

If the context property changes, then the form is re-renders, for this reason the object used for the context should be referential stable (the reference should not change across re-renders unless the values actually changes), it should be stored in a state, constant or with useRef.

The example below causes unwanted re-renders of the form every time the view MyView re-renders, that's because a new reference is passed to the context property

// this is wrong!
const MyView = () => {
  return (
    <LetsForm
      form={MY_FORM}
      context={{
        token: 'my-token'
      }}
    />
  );
};