I am working on a global storage of user information coming from the server. To do this, I want to utilize React Context API. The method seems to work with the child routes/functions, but in the Parent (index.js) it cannot read any value and gets the error “TypeError: Cannot destructure property ‘user’ of ‘Object(…)(…)’ as it is undefined”. Why can all my child components read and update the user context but not the Parent (index.js)? Btw, same approach here as used in the child components.
UserConext.js
import { createContext, useState } from "react";
export const UserContext = createContext();
// This context provider is passed to any component requiring the context
export const UserProvider = ({ children }) => {
const [user, setUser] = useState({
id: 0,
name: ""
});
return (
<UserContext.Provider value={{user, setUser}}>
{children}
</UserContext.Provider>
);
};
Index.js (Parent)
import React, { useState, useEffect, useContext } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './components/Login/Login';
import Registration from './components/Registration/Registration';
import RegistrationConfirmed from './components/Confirmation/RegistrationConfirmed'
import Home from './components/Home/Home';
import myProfile from './components/Profile/myProfile';
import ProtectedRoute from './ProtectedRoute';
import { AuthContext } from './components/Context/AuthContext';
import Axios from 'axios';
import {UserContext, UserProvider} from './components/Context/UserContext';
function App () { //Exact path = Beginning page of the site
const [authStatus, setAuthStatus] = useState(AuthContext);
const {user, setUser} = useContext(UserContext);
useEffect(() => { //Stay logged in, if user is logged in, after refresh
const token = localStorage.getItem('token');
Axios.post("http://localhost:3001/authenticate", { //End-point for creation request
token: token,
},{withCredentials: true}).then(response => {
if (!response.data.auth) { //checking for response message
setAuthStatus(false); //Login status is
localStorage.clear();
console.log("NOT LOGGED IN!");
} else {
setAuthStatus(true);
console.log("LOGGED IN!");
setUser({id: JSON.stringify(response.data.user[0]).id, name: JSON.stringify(response.data.user[0]).name});
})
}
,[]);
return (
<AuthContext.Provider value={[authStatus, setAuthStatus]}>
<UserProvider>
<Router>
<Switch>
<Route exact={true} path="/" component={Login} />
<Route path="/Registration" component={Registration} />
<Route path ="/Confirmation" component={RegistrationConfirmed}/>
<ProtectedRoute path="/home" component ={Home} authStatus = {authStatus}/>
<ProtectedRoute path = "/myProfile" component={myProfile} authStatus = {authStatus}/>
</Switch>
</Router>
</UserProvider>
</AuthContext.Provider>
);
};
render(
<App />, document.getElementById('root')
);