testingtestinganyone
testingtestinganyone

Reputation: 497

React context is returning undefined

Not sure why this is happening, I have checked to make sure that the states value is not undefined which it isnt and i cant see where im going wrong.

My authContext.js file

const initialState = {
  isAuthorized: false,
}

export const authContext = React.createContext() 

export default function AuthContextComp(props) {
  const [state, dispatch] = useReducer(reducer,initialState)

  return (
    <authContext.Provider authState={state}>
      {props.children}
    </authContext.Provider>
  )
}

function reducer(state, action){
  switch (action.type) {
    case 'signIn':
      return true;
      break;
  
    default:
      return state;
  }
}

My app file

function MyApp({ Component, pageProps, appProps }) {

  return (
    <GlobalContextWrapper pageData={pageProps}>
      <AuthContextWrapper>
        <div style={{textAlign:'center',paddingTop: 200}}>
          <h2>Signed in</h2>
          <button>Log in or log out</button>
          <Component {...pageProps} />
          <Test/>
        </div>
      </AuthContextWrapper>
    </GlobalContextWrapper>
  );
}

export default MyApp;

The component im trying to use the context in

import React, {useContext} from 'react'
import {authContext} from '../global/authContext/AuthContext'

export default function Test() {
  const t = useContext(authContext)
  return (
    <div>
       This is the test component
    </div>
  )
}

Can you see anything wrong here? Im using next.js and i cant figure out why not

Upvotes: 1

Views: 1787

Answers (1)

testingtestinganyone
testingtestinganyone

Reputation: 497

Issue was that when passing state into the provide the name should be value. Not sure why this would be the case

    <authContext.Provider  value={state}>
      {props.children}
    </authContext.Provider>

Upvotes: 3

Related Questions