0

I have a blog application created in nextjs. I want to fetch menus (nav) from the api and load to Nav component. But how can I fetch menus on every refresh and save it to react context api? I have tried fetch menus from home page and save it to react context api, but on other pages menus are not available.

const MyApp = ({ Component, pageProps }) => {
  const [queryClient] = React.useState(() => new QueryClient());

  return (
    <AppProvider>
      <QueryClientProvider client={queryClient}>
        <Hydrate state={pageProps.dehydratedState}>
          <Component {...pageProps} />
          <ReactQueryDevtools />
        </Hydrate>
      </QueryClientProvider>
    </AppProvider>
  );
};

MyApp.getInitialProps = async (appContext) => {
  const appProps = await App.getInitialProps(appContext);

  const response= await apiClient().get('/api/index');

  const { setMenus } = useAppContext(); // This line not working
  setMenus(response.data);

  return { ...appProps };
};
2
  • In your example, YOU DON'T NEED CONTEXT since you drilled the props to every Component through pageProps, your response already on every entry page props. Use the response to pass in addition to {...appProps, menus: response.data} Commented Jul 26, 2021 at 8:33
  • @DennisVash Then, how can I access menus from other components? Commented Jul 26, 2021 at 8:39

1 Answer 1

1

Not sure what your stragedy here, but you can go either way, pass the menu to your provider or use the drilled props:

const MyApp = ({ Component, pageProps }) => {
  // OR pass those menus to the provider
  const {menus} = pageProps;


  // OR the response already passed to every page entry point at pageProps
  return (
    <AppProvider value={menus}>
      <Component {...pageProps} />
    </AppProvider>
  );
};

MyApp.getInitialProps = async (appContext) => {
  const appProps = await App.getInitialProps(appContext);

  const response= await apiClient().get('/api/index');
  return { ...appProps, menus: response.data };
};

// Now from every entry page like MenuPage, the menu should be available OR use it as context consumer
const MenuPage = ({menu}) => {...}
Sign up to request clarification or add additional context in comments.

5 Comments

Then, how can I access menus from other components?
To which of the methods you refer to? Also I mentioned it in the answer
Thank you. Last question, is this a best way to load menus to navigation that are dynamic?
Sounds reasonable solution, "best way" is opinionated.
I tried to get menus from component but it undefined?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.