Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React context return undefined

Tags:

reactjs

I am using React Context api to pass some states to different child components and it's returning undefined.

Parent component:

export const UserContext = React.createContext();
export class Provider extends Component {
  state = {
    editGroup: false,
  }
  render() {
    return (
      <UserContext.Provider value={{
        state: this.state
      }}>
        {this.props.children}
      </UserContext.Provider>
    )
  }
}

Child component:

import { UserContext } from './index';

return (
  <React.Fragment>
    <UserContext.Consumer>
      {(context) => (
        <p>im inside the consumer {console.log(context)}</p>
      )}
    </UserContext.Consumer>
  </React.Fragment>
);

This last console.log is returning as undefined, what am I doing wrong here ?

like image 758
vbotio Avatar asked Dec 14 '18 00:12

vbotio


1 Answers

Also, make sure to pass context in the constructor if you override it!

    export default class Profile extends React.Component {
        static contextType = AuthContext;
        // make sure you pass the context along to super!
        constructor(props, context) {
            super(props, context);
            ...
        }
    }
like image 181
Kenneth Lynne Avatar answered Sep 18 '22 03:09

Kenneth Lynne