-1

I have a next.js app where I am trying to use react context to export a state. However, the state is not updating and remains as the initial value set by the createContext hook which is undefined in this case. Am I doing something wrong?

This is the file where I create the context:

import { NextPage } from 'next';
import {
  useState,
  SyntheticEvent,
  createContext,
  useContext,
  ReactNode,
} from 'react';
import { TimeZoneType } from '../CompetitionList/types';

interface Props {
  children: ReactNode;
}

type ContextType = {
  timeZone: TimeZoneType;
  handleTimeZone: (_event: SyntheticEvent, _newZone: TimeZoneType) => void;
};

const TimeZone = createContext<ContextType>({} as ContextType);

const TimeZoneState: NextPage<Props> = ({ children }) => {
  const [timeZone, setTimeZone] = useState<TimeZoneType>('Local');
  const handleTimeZone = (_event: SyntheticEvent, newZone: TimeZoneType) => {
    if (newZone !== null) {
      setTimeZone(newZone);
    }
  };
  return (
    <TimeZone.Provider value={{ timeZone, handleTimeZone }}>
      {children}
    </TimeZone.Provider>
  );
};

export const useTimeZone = () => {
  return useContext(TimeZone);
};

I call the context similar to this:

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
console.log({timeZone})
//returns undefined

Sorry if this is a bad question it is my first one.

Anonymouse
  • 91
  • 1
  • 7
  • Where did you place your context provider? Make sure the component you’re using the context in is inside your provider. – SamiElk Feb 10 '22 at 08:54
  • @SamiElk I put my context provider near the end of the first code block at '../components/GlobalVariables/TimeZone' and am using {children} inside the provider. Is this how I'm supposed to get the state value in a different file? – Anonymouse Feb 10 '22 at 18:52

1 Answers1

0

I think I found a workaround. I just needed to wrap my TimeZone.Provider around the components where I wanted to use my context. So, I exported the TimeZoneState function and wrapped it around my page components in _app.tsx like this:

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <TimeZoneState>
      <Component {...pageProps} />
    </TimeZoneState>
  );
};

export default MyApp

This allowed me to use my context inside my pages how I wanted to.

import { useTimeZone } from '../components/GlobalVariables/TimeZone';
...

const { timeZone, handleTimeZone } = useTimeZone();
Anonymouse
  • 91
  • 1
  • 7