Created
October 14, 2021 19:16
-
-
Save Brlaney/73d9b044ccb6fe6a94b6b8c7685c09ca to your computer and use it in GitHub Desktop.
A Redirect component I continuously re-use in Next.js apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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