Every time I run yarn start with the following line of code const context = useContext(GlobalContext); I run into this "Error: Invalid hook call. Hooks can only be called inside of the body of a function component." How can I fix this it's driving me mental. here's a screenshot showing the error, the dependencies and my code error message and react dependecies

here is the code for my globalState if that's whats causing it

import React, { createContext, useReducer } from "react";
import AppReducer from './AppReducer';

// initial state
const initialState = {
    healthData:
        { age: "38", gender: "male", goal: "Lose", height: "180.34", weight: 80 }

}

export const GlobalContext = createContext(initialState);

// provider component
export const GlobalProvider = ({ children }) => {
    const [state, dispatch] = useReducer(AppReducer, initialState);


    return (<GlobalContext.Provider value={{
        healthData: state.healthData
    }}>
        {children}
    </GlobalContext.Provider>);
}

export default (state, action) => {
    switch(action.type) {
        default:
            return state;
    }
}

  return (
      <div>
        <Router>
          <div className='App'>
            {this.state.user ? (<Nav drawerClickHandler={this.drawerToggleClickHandler} />) : (<Login_bar />)}
            <SideDrawer sidedrawerClickHandler={this.sidedrawerToggleClickHandler} show={this.state.sideDrawerOpen} />
            {backdrop}
            <GlobalProvider>
              {this.state.user ?
                (< Switch >
                  <Route path='/settings_page' component={settings_page} exact />,
                  <Route path='/setup_page' component={setup_page} exact />,
                  <Route path='/' component={Main_page} />
                </Switch>) : (<Login_page />)}
            </GlobalProvider>
          </div>
        </Router>
      </div >

    );

So I've done some research into this and apparently it's likely that either my react or react-dom are not up to date. Iv tried updating both multiple time and running npm install. didn't fix my issue, I'm also almost certain that I'm calling on hooks correctly. Another thing is my global state is set up correctly because I can see it in the react chrome extension.

1

There are 1 best solutions below

6
On

Thats because Hooks can not be used in a class based component. Alternatively you can create a HOC component an use it in your class based component, or covert your class component into functional component.