'Nextjs update state from inside `getServerSideProps`
import "../styles/globals.css";
import type { AppProps } from "next/app";
import { Router } from "next/router";
import { Loading } from "../components";
import React, { createContext, useState } from "react";
export type LoadingContextType = {
loading: boolean;
setLoading: (loading: boolean) => void;
};
export const LoadingContext = createContext<LoadingContextType>({
loading: false,
setLoading: () => {},
});
function MyApp({ Component, pageProps }: AppProps) {
const [loading, setLoading] = useState(false);
Router.events.on("routeChangeStart", () => {
setLoading(true);
});
Router.events.on("routeChangeComplete", () => {
setLoading(false);
});
return (
<>
<LoadingContext.Provider value={{ loading, setLoading }}>
<div style={{ display: `${loading ? "none" : "block"}` }}>
<Component {...pageProps} />
</div>
</LoadingContext.Provider>
</>
);
}
export default MyApp;
my _app has loading state and I'm passing that state in context API <LoadingContext.Provider value={{ loading, setLoading }}>.
import { NextPage } from "next";
import { useContext } from "react";
import { LoadingContext } from "./_app";
type PageProps = {
loadingState: boolean;
};
const About: NextPage<PageProps> = ({}) => {
return (
<div>
<p>About Page</p>
</div>
);
};
export async function getServerSideProps() {
return {
props: {
loadingState: false,
},
};
}
export default About;
this is About page how can update _app state from About's getServerSideProps?
now I know that getServerSideProps is server side and can't access React useContext so what other ways can I do it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
