Reputation: 123
App.js
import React, { Component } from 'react';
import { Router, Route, browserHistory } from 'react-router';
import Login from './Login';
import Courses from './Courses';
class App extends Component {
constructor() {
super();
this.state = {
username: '',
password: ''
};
}
setCredentials = ({ username, password }) => {
this.setState({
username,
password
});
}
render() {
return (
<Router history={browserHistory}>
<Route
path='/'
component={Login}
setCredentials={this.setCredentials}
/>
<Route
path='/courses'
component={Courses}
credentials={this.state}
/>
</Router>
);
}
}
The Login
component takes in credentials from user, verifies them via an API call, updates App
's state with them, and then redirects to the Courses
component using this.props.router.push('/courses')
.
The Courses
component should take in the updated credentials (i.e. App
's updated state) as props, and afterwards perform an API call to fetch that user's courses.
How can I detect the updates in App
's state inside the Courses
component? Am I doing it wrong altogether?
Upvotes: 1
Views: 2082
Reputation: 93531
<Route
path='/'
component={(props) => <Login setCredentials={this.setCredentials} {...props} />}
/>
and NOT:
<Route
path='/'
component={Login}
setCredentials={this.setCredentials}
/>
The same for the Courses
component, you pass extra-props the same way:
<Route
path='/courses'
component={(props) => <Courses credentials={this.state} {...props} />}
/>
And NOT:
<Route
path='/courses'
component={Courses}
credentials={this.state}
/>
Which answers the question:
How can I detect the updates in App's state inside the Courses component?
since crendentials
becomes a prop of Courses
and its value state
of App
.
Upvotes: 2
Reputation: 223
As you said with the courses component reading from props you could have a lifecycle hook like so in the courses component:
componentWillReceiveProps(nextProps) {
if(nextProps.isAuthenticated && this.props.credentials !== nextProps.credentials) {
// perform fetch for courses here
}
}
Upvotes: 0