React Context value not defined inside click handler

Viewed 323

I have a functional component in which I am trying to use context, I get the value during import, but when I want to use it inside click handler, says its not defined

component.js

// I get these values over here
const [contextState, setContextState] = useContext(MyContext);
const clickHandler = (e) => {
    debugger; // when I am trying to log any of these values I get error of not defined
}

return (<button onClick={clickHandler}>Click me!</button>);

Moreover I have wrapped my app.js components as below

import { MyContextProvider } from './MyContext';
return (
    <Router>
        <MyContextProvider>
            <div className='App'>
                <Component />
            </div>
        </AuthContextProvider>
    </Router>
);

Now my context file, myContext.js

import React, { useState, createContext } from 'react';

const MyContext = createContext([{}, () => {}]);

const MyContextProvider = (props) => {
    const [contextState, setContextState] = useState({
        userIsLoggedin: false,
        fName: '',
        lName: '',
        userName: ''
    });
    return (
        <myContext.Provider value={[contextState, setContextState]}>
            {props.children}
        </myContext.Provider>
    );
};

export { myContext, MyContextProvider };
3 Answers

It looks like you have some typos in your context file. First, use MyContext everywhere in that file (not myContext), and second, pay attention to the variable names you're specifying when you first call useState and then pass that same value to the context (authState vs contextState):

import React, { useState, createContext } from "react";

const MyContext = createContext([{}, () => {}]);

const MyContextProvider = props => {
  const [authState, setAuthState] = useState({
    userIsLoggedin: false,
    fName: "",
    lName: "",
    userName: ""
  });
  return (
    <MyContext.Provider value={[authState, setAuthState]}>
      {props.children}
    </MyContext.Provider>
  );
};

export { MyContext as default, MyContextProvider };

Here's a working codesandbox with your setup

So, I have debugged over and over again only to find out that it is not reading in debugger but value is getting printed in console.log() and while using it in code directly.

It appears there is some issue with chrome debugger in the current version.

So, anyone facing this issue please try using the variable or log it if on chrome

update : it doesn't print in debugger, but it works with log. Probably it is expected, but it works

I think, You Need to Bind the event listener or use array func,

return (<button onClick={clickHandler.bind(this)}>Click me!</button>);
// Or,
return (<button onClick={ev => clickHandler(ev)}>Click me!</button>);
Related