'Send values from one browser tab to another in nextjs and populate formik form
I have a form in next with a single input e.g. name on my page. On submit I would like the browser to open a new tab which contains a form with more inputs e.g. name, address, age. How can I pre-populate the name in the new tab?
I was considering the useContext hook but as far as I can tell that does not work across tabs. Do I need to use Redux at this point?
Edit: My attempt using localStorage so far:
// User inputs name which on submit is
// saved to local storage and /register page is opened
const Home: NextPage = () => {
return (
<Formik
initialValues={{ name: '' }}
onSubmit={(values) =>
localStorage.setItem('name', values.name)
}
>
{() => (
<Form>
<div>
<InputBox
type="text"
id="name"
name="name"
htmlFor="name"
label="Name"
placeholder=""
/>
<button
type="submit"
// ? Not sure using window is the correct way to do this in nextjs
onClick={(event) => window.open('/register', '_blank')}
>
Start KYC
</button>
</div>
</Form>
)}
</Formik>
)
import { Field, Form, Formik } from 'formik'
import { NextPage } from 'next'
import React from 'react'
const Register: NextPage = () => {
let nameInit = ''
React.useEffect(() => {
if (typeof window !== 'undefined') {
console.log('You are on the browser')
// 👉️ can use localStorage here
} else {
console.log('You are on the server')
// 👉️ can't use localStorage
}
nameInit = localStorage.getItem('name') ?? ''
console.log(nameInit)
}, [])
return (
<Formik
initialValues={{
name: nameInit,
}}
onSubmit={async (values) => {
console.log(values)
}}
>
{() => (
<Form className="space-y-8 divide-y divide-gray-200">
<div className="sm:col-span-2">
<label
htmlFor="name"
>
First name
</label>
<Field
type="text"
name="name"
id="name"
autoComplete="given-name"
/>
</div>
<div className="flex justify-end">
<button
type="submit"
>
Submit
</button>
</div>
</Form>
)}
</Formik>
)
}
Inspecting the page I can see that the value is being set and the console.log at the end of the useEffect also returns the expected value. But the form is still not being populated... My guess is the form is rendered before the useEffect is executed? When I just write the code in the function body instead of using useEffect it seems that is being executed on the server where localStorage is not available.
Solution 1:[1]
You're closer than you think! It works across tabs, but you might be using <link> or <a> tags to navigate.
If you use the built in next/link, your app won't refresh and useContext will work for you. Your app will also take advantage of Next JS's speed optimisations. Example:
import Link from "next/link"
const Nav = () => (
<Link href="gosomewhere">
<a>I'm a Link</a>
</Link>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | P Savva |
