1

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

7
  • authContext.Provider does this need to be captialised? AuthContext.Provider Commented Feb 2, 2021 at 20:48
  • @evolutionxbox no it does not. Commented Feb 2, 2021 at 20:48
  • @PatrickRoberts is it a convention? React docs say "Note: Always start component names with a capital letter." Commented Feb 2, 2021 at 20:49
  • @evolutionxbox the component name is Provider. Commented Feb 2, 2021 at 20:50
  • 1
    Correct @evolutionbox - I thought you could name it anything but apparently not! Commented Feb 2, 2021 at 20:54

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

To elaborate slightly on @PatrickRoberts terse response, the Provider component is internally defined by React when you create the context. In that definition, it has a value prop that takes the type the Context holds. It's "just how it works" :)

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.