I recently try to implement context in my React app but I just can't access to my context on a chlid component.
The principle is as follows: The index.js provide a context who declare a value which correspond to the logged status of an user (false by default).
If App.js detects a JWT store in the localstorage, so the context is updated to true and a certain component is render.
Here is the Code:
AppContext.js
import React from 'react'
export const AppContext = React.createContext({
isUserLogged: false
})
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import './assets/sakura/app.css'
import App from './components/App'
import * as serviceWorker from './serviceWorker'
import { AppContext } from './context/AppContext'
ReactDOM.render((
<AppContext.Provider>
<App />
</AppContext.Provider>
), document.getElementById('root'));
App.js
import React from 'react'
import Auth from './auth/Auth'
import Main from './main/Main'
import { AppContext } from '../context/AppContext'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
userToken: localStorage.getItem('spotlight-token'),
isUserLogged: false
}
}
UNSAFE_componentWillMount() {
if (this.state.userToken) this.setState({isUserLogged: true})
}
static contextType = AppContext
render() {
console.log(this.context)
const isUserLogged = this.state.isUserLogged
return isUserLogged ? <Main /> : <Auth />
}
}
export default App
But the problem is here, the console returns undefined and I don't understand why.
Thank you for your help, I know it may sound slightly stupid but I'm a pure beginner width context and really want to understand it.