Home > Back-end >  I keep getting an invalid hook call error
I keep getting an invalid hook call error

Time:03-17

I keep getting an invalid hook call error while i am working on my project, this is the only hook I am using, and I am only using it in these two places and my Instructors don't understand why I am getting this error either. I am at a total loss and I have no clue how to move forward because my app needs to use context.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { FoodProvider } from './FoodContext';
import { BrowserRouter as Router } from 'react-router-dom'

ReactDOM.render(
  <Router>
    <FoodProvider>
      <App />
    </FoodProvider>
   </Router>,
  document.getElementById('root')
);

...

import logo from './logo.svg';
import './App.css';
import Navbar from './Navbar';

function App() {
  return (
    <div className="App">
      <Navbar/>
    </div>
  );
}

export default App;

...

import React from 'react'
export default function Navbar() {
    return (
        <div className="navbar">
            <div className="nav-head">
                <h1>Meals <span>App</span></h1>
            </div>
            <div className="nav-links">
                <ul>
                    <li>Home</li>
                    <li>Catagories</li>
                    <li>Random</li>
                </ul>
            </div>
        </div>
    )
}

...

import React,{useContext} from "react";

const FoodContext = useContext()

function FoodProvider(props){
    return(
        <FoodContext.Provider value =''>
            {props.children}
        </FoodContext.Provider>
    )

}


export {FoodContext, FoodProvider}

CodePudding user response:

You are incorrectly using the useContext hook instead of the createContext function.

import { createContext, useContext } from 'react';

// Create a React Context
const FoodContext = createContext(/* set any default value here */);

// Create a custom hook
const useFoodContext = () => useContext(FoodContext);

// Create Provider component
function FoodProvider({ children }) {
  return(
    <FoodContext.Provider value={/* pass a context value here */}>
      {children}
    </FoodContext.Provider>
  );
}

export { FoodContext, useFoodContext };
export default FoodProvider;

...

import FoodProvider from './FoodContext';
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <FoodProvider>
      <App />
    </FoodProvider>
   </Router>,
  document.getElementById('root')
);
  • Related