I'm just getting started with React and i tried to write a simple context that will store the details of the user.
AuthProvider.js
import React, {useState,useEffect,createContext } from 'react';
export const AuthContext = createContext();
export const AuthProvider = ({children}) => {
const [user, setUser] = useState(null);
useEffect(() => {
const currentUser = {id:1,role:'user'} //here get user from server
setUser(currentUser)
}, []);
return (
<AuthContext.Provider value={{ user }} >{children}</AuthContext.Provider>
);
};
useAuth.js
import {useContext} from 'react';
import { AuthContext } from './AuthProvider';
const useAuth = () => {
const user = useContext(AuthContext);
if (user === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return user;
};
export default useAuth;
App.js
import {HashRouter, Routes, Route} from "react-router-dom";
import {AuthProvider} from './context/AuthProvider';
import Home from "./pages/Home";
import './App.css';
function App() {
return (
<AuthProvider>
<HashRouter>
<Routes>
<Route exact path="/" element={<Home/>}></Route>
</Routes>
</HashRouter>
</AuthProvider>
);
}
export default App;
Home.js
import React from 'react'
import useAuth from '../context/useAuth'
function home() {
const { user } = useAuth();
return (
<div>home</div>
)
}
export default home
But when i try to use "useAuth" i have error:
src\pages\Home.js
Line 6:22: React Hook "useAuth" is called in function "home" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".
Can someone explain to me what the problem is and how can I fix it?