use mutate to trigger re-fetch for signup list

This commit is contained in:
Aarni Halinen
2021-06-29 14:10:09 +03:00
parent 086dc5e405
commit 7b801eb285
+15 -6
View File
@@ -3,6 +3,8 @@ import { NextPage, GetStaticProps, GetStaticPaths } from "next";
import Head from "next/head";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import axios from "axios";
import useSWR, { mutate } from "swr";
import { Signup, SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";
import SignUpPageView from "@views/SignUpPage/SignUpPageView";
@@ -12,11 +14,18 @@ import noop from "@utils/noop";
import NotFoundPage from "@pages/404";
type InitialProps = {
form: SignupForm;
initialForm: SignupForm;
};
const SignUpPage: NextPage<InitialProps> = ({ form }) => {
const FORM_URL = `${process.env.NEXT_PUBLIC_API_URL}/signupForm/`;
const SignUpPage: NextPage<InitialProps> = ({ initialForm }) => {
const router = useRouter();
const id = String(initialForm.id);
const URL = `${FORM_URL}${id}/`;
const signupResult = useSWR(URL, (url) => axios.get(url).then((res) => res.data), { initialData: initialForm });
const form = signupResult.data ?? initialForm;
if (router.isFallback) {
return <LoadingView />;
@@ -37,7 +46,7 @@ const SignUpPage: NextPage<InitialProps> = ({ form }) => {
try {
await SignupApi.createSignup(payload);
toast.success("Sign-up submitted successfully 😎");
router.push(window.location.href); // TODO: Fetch/update signup list, so user sees the signup in the list
mutate(URL);
} catch (error) {
console.error(error);
toast.error("Uh oh! Sign-up failed! 😟");
@@ -78,15 +87,15 @@ export const getStaticPaths: GetStaticPaths = async () => {
export const getStaticProps: GetStaticProps<InitialProps> = async ({ params }) => {
const { id } = params;
let notFound = false;
let form: SignupForm;
let initialForm: SignupForm;
try {
form = await SignupApi.getForm(Number(id));
initialForm = await SignupApi.getForm(Number(id));
} catch {
notFound = true;
}
return {
props: {
form,
initialForm,
},
revalidate: 10,
notFound,