Skip to content

Instantly share code, notes, and snippets.

@Brlaney
Created October 14, 2021 19:16
Show Gist options
  • Save Brlaney/73d9b044ccb6fe6a94b6b8c7685c09ca to your computer and use it in GitHub Desktop.
Save Brlaney/73d9b044ccb6fe6a94b6b8c7685c09ca to your computer and use it in GitHub Desktop.
A Redirect component I continuously re-use in Next.js apps
import { useEffect } from 'react';
import { useRouter } from 'next/router';
const Redirect = ({ to }) => {
const router = useRouter();
useEffect(() => {
router.push(to)
}, [to])
return null
};
export default Redirect;
/* Example of importing/using:
import Redirect from '@/components/Redirect';
...
const [shouldRedirect, setShouldRedirect] = useState(false);
if (shouldRedirect) {
return <Redirect to='/create/success' />
};
...
const handleSubmit = async (e: { preventDefault: () => void }) => {
e.preventDefault()
try {
const response = await fetch(`${server}/companies`, {
method: 'POST',
headers,
body: JSON.stringify(modifiedData),
})
.then(checkStatus)
.then(parseJSON)
setShouldRedirect(true)
} catch (error) {
setErrorCompanies(error)
}
};
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment