I have a form composed of several input components. The form data is shared and shareable across these sibling components via a React context and the React hook useContext
.
I am stumbling on how to optionally async load data into the same context. For example, if the browser URL is example.com/form
, then the form can load with the default values provided by a FormContext
(no problem). But if the user is returning to finish a previously-edited form by navigating to example.com/form/:username/:form-id
, then application should fetch the data using those two data points. Presumably this must happen within the FormContext somehow, in order to override the default empty form initial value.
- Are url params even available to a
React.createContext
function? - If so, how to handle the optional data fetch requirement when hooks are not to be used with in a conditional?
- How to ensure that the data fetch occurs only once?
- Lastly, the form also saves current state to local storage in order to persist values on refresh. If the data fetch is implemented, should a refresh load the async data or the local storage? I'm leaning towards local storage because that is more likely to represent what the user last experienced. I'm open to opinions and thoughts on implementation.
FormContext
export const FormContext = React.createContext();
export const FormProvider = props => {
const defaultFormValues = {
firstName: "",
lastName: "",
whatever: "",
};
const [form, setForm] = useLocalStorage(
"form",
defaultFormValues
);
return (
<FormContext.Provider value={{ form, setForm }}>
{props.children}
</FormContext.Provider>
);
};
Reference for useLocalStorage