How to use contextAPI in nextjs

Viewed 593

I created a context Provider to handle authentication for specific pages. Using Firebase client auth, it listens for changes in authentication state and update a user state, which can be accessed by any page using useAuth, provided the page or its parent is wrapped with the AuthContextProvider

The Context API is not working as expected in Nextjs. Fails on every build attempt.

service/auth.context.js file

import React, {useState, createContext, useEffect, useContext} from "react";
import LogIn from "../../components/adminUI/auth/Login";
import {auth} from "../firebase";

const AuthContext = createContext({user: null, isLoding: false, error: null});

const AuthContextProvider = (props) => {
  const [user, setUser] = useState(null);
  const [isLoding, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    // listen for auth state changes
    auth.onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
      console.log("user> ", user);
    });
  });

  /**
   * render given component
   * @param {object} children
   */
  const renderAuth = (children) => {
    <div>
      {children}
    </div>;
  };

  // if not authenticated, render Login
  if (!user) return renderAuth(<LogIn/>);
  
  return <AuthContext.Provider value={{user, isLoding, error}}>
    {props.children}
  </AuthContext.Provider>;
};

export const useAuth = () => useContext(AuthContext);
export default AuthContextProvider;

pages/cms/index.js

import DashboardPage from "../../components/adminUI/dashboard";
import AuthContextProvider from "../../lib/services/auth.context";

const Cms = (props) => {
   return <>
     <AuthContextProvider>
       <DashboardPage/>
     </AuthContextProvider>
   </>;
 };
    
export default Cms;

Here's the Error from next build

info  - Collecting page data
[=   ] info  - Generating static pages (0/6)
Error occurred prerendering page "/cms". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Minified React error #152; visit https://reactjs.org/docs/error-decoder.html?invariant=152&args[]=AuthContextProvider for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
...

info  - Generating static pages (6/6)

> Build error occurred
Error: Export encountered errors on following paths:
        /cms

I expect a complete build & a on running app, 'https://.../cms' should display the LogIn component

Is the implementation wrong? I'm new to Next.js

1 Answers

You're missing a return statement before the JSX inside the renderAuth function.

const renderAuth = (children) => {
    return (
        <div>
            {children}
        </div>
    );
};

Or alternatively, using short-hand syntax.

const renderAuth = (children) => (
    <div>
        {children}
    </div>
);
Related