Persist Form state across locations like browser's non-SPA default behavior #9947
ryanflorence
started this conversation in
Proposals
Replies: 1 comment
-
I'm hacking together something similar in my project using react-router as the base. The only thing I'm currently missing is a way to define an initial state for formData when action is invoked / form is rendered . Is there any way I can set an initial value to the // actions to be used with every form step
async function loadInitalFormdataAction({ request }: any) {
const data = await request.formData()
return data
}
// Link that returns current state of form when going back
<Link to="/affecte/produit" state={defaultData}>previous</Link>
// a custom hook that merges the two states
export function useDefaultData() {
const forward_data = useActionData() as FormData | undefined
const location = useLocation()
const reverse_data = location.state as FormData | undefined
const defaultData = mergeFormdata(new FormData(), [
forward_data,
reverse_data,
])
return defaultData
}
//Missing
<Form action="/next-step" initalData={defaultData}>...</Form> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When you enter values in a form field and click a link, and then click the back button, the browser automatically restores the values in the form fields. Super valuable when you're writing up a proposal for React Router and accidentally hit
command+[
.It's the same kind of behavior as the browser's default behavior with scroll restoration, something React Router now emulates for
pushState
client side navigation.(Of course, browsers should just do this for us by default but the history API is bootleg, so here we are)
React Router could emulate this behavior, too with an identical strategy to scroll restoration:
location.key
<Form>
mounts restore the values ifinput.defaultValue !== input.value
It might be hard to identify one form from another. We could do best guess based on the order of the forms in the DOM, or serialize the form's attributes and form element attributes to try to identify it, or simply require an ID.
I think I'd like this to be the default behavior, which would be breaking change, so we could introduce "future flags" in react router (Matt and I have already discussed this) to opt-in to the behavior globally and then flip it to the default in v7.
And you'd be able to opt out with something like
<Form restore="off">
, mimicking the<form autocomplete="on|off">
API.Beta Was this translation helpful? Give feedback.
All reactions