Home > Blockchain >  How to share state between NextJS components
How to share state between NextJS components

Time:03-27

I want to pass a state between pages in Next.js. My App.js is wrapped in a context provider like so

import { useRouter } from 'next/router'
import { ClickProvider } from '../context/clickContext'

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  
  return (
        <ClickProvider>
                <Component {...pageProps} key={router.asPath} />
        </ClickProvider>
  )
}

export default MyApp

Here's my context provider

import { createContext, useState } from 'react';

const MenuContext = createContext()

export const ClickProvider = ({ children }) => {
  const [menuEnterPage, setMenuEnterPage] = useState('');

  return (
    <MenuContext.Provider value={[menuEnterPage]}>
      {children}
    </MenuContext.Provider>
  );
};

export default MenuContext;

Inside my header component I want to set the menuEnterPage to be the path of the page the user tapped the button on and that data to persist between pages.

import Link from 'next/link'
import React, { useContext, useState, useEffect, useRef } from "react";
import { useRouter } from "next/router"
import MenuContext from '../context/clickContext';

export default function Header({mobileHidden, router = useRouter()}) {
    const [isActive, setActive] = useState(mobileHidden);
    const [menuEnterPage, setMenuEnterPage] = useContext(MenuContext);

    const handleToggle = () => {
      setActive(!isActive);
      if (isActive) {
        
      } else {
        setMenuEnterPage(router.asPath)
        console.log(menuEnterPage)
      }
    };

    return (
      <header>
            <button className="md:hidden" onClick={handleToggle}>{isActive ? "Menu" : "Exit" }</button>
    </header>
    );
  }

Currently when I run the project and click the button it fails with error

TypeError: setMenuEnterPage is not a function

CodePudding user response:

Try to change this

<MenuContext.Provider value={[menuEnterPage]}>

to this

<MenuContext.Provider value={[menuEnterPage, setMenuEnterPage]}>
  • Related