Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  11] [ 3]  / answers: 1 / hits: 31214  / 6 Years ago, tue, april 3, 2018, 12:00:00

I'm trying to use the new React context to hold data about the logged-in user.



To do that, I create a context in a file called LoggedUserContext.js:



import React from 'react';


export const LoggedUserContext = React.createContext(
);


And sure enough, now I can get access to said context in other components using consumers, as I do here for example:



  <LoggedUserContext.Consumer>
{user => (
(LoggedUserContext.name) ? LoggedUserContext.name : 'Choose a user or create one';
)}
</LoggedUserContext.Consumer>


But obviously, for this system to be useful I need to modify my context after login, so it can hold the user's data. I'm making a call to a REST API using axios, and I need to assign the retrieved data to my context:



axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { /*What should I do here?*/});


I see no way to do that in React's documentation, but they even mention that holding info of a logged in user is one of the use cases they had in mind for contexts:




Context is designed to share data that can be considered “global” for
a tree of React components, such as the current authenticated user,
theme, or preferred language. For example, in the code below we
manually thread through a “theme” prop in order to style the Button
component:




So how can I do it?


More From » reactjs

 Answers
20

In order to use Context, you need a Provider which takes a value, and that value could come from the state of the component and be updated



for instance



class App extends React.Component {
state = {
isAuth: false;
}
componentDidMount() {
APIcall().then((res) => { this.setState({isAuth: res}) // update isAuth })
}
render() {
<LoggedUserContext.Provider value={this.state.isAuth}>
<Child />
</LoggedUserContext.Provider>
}
}


The section about dynamic context explains it


[#54783] Friday, March 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eanskylerg

Total Points: 524
Total Questions: 107
Total Answers: 100

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
;