100 - Redux Chili Peppers 'Again'
Tu as découvert Redux dans la quête précédente, mais il reste encore quelques astuces à apprendre avant de pouvoir te considérer comme maître de l'outil.
Objectifs
- Permettre à une application React de communiquer avec le serveur de manière authentifiée
1 - 1 action, n reducers
Il arrive souvent qu'une action, à un endroit donné de l'application, impacte plusieurs states. Par exemple, jusqu'à présent, le Snackbar a été implémenté à l'intérieur d'un container (composant React connecté au store Redux) SignIn ou Profile. Pourtant, il serait sans doute plus judicieux d'avoir un composant PopUp qui gérera l'affichage de manière centralisée. Par conséquent, lorsqu'on se connecte, l'action met à jour le token (jeton d'authentification) dans le reducer auth, mais on a aussi besoin du msg dans le reducer flash.
2 - Supprime tous les Snackbar de ton application
Avant de continuer, supprime tous les composants Snackbar de ton application.
3 - Crée un container PopUp
Dans un fichier PopUp.jsx, saisis le code suivant :
import React, { Component } from 'react'
import {connect} from 'react-redux'
import Snackbar from 'material-ui/Snackbar';
class PopUp extends Component {
constructor(props) {
super(props);
this.state = {
flash: ""
};
}
componentWillReceiveProps(nextProps){
this.setState({flash: nextProps.flash})
}
handleClose = () => {
this.setState({flash: ""});
};
render() {
return (
<Snackbar
open={this.state.flash !== ""}
message={this.state.flash}
autoHideDuration={2000}
onClose={this.handleClose}
/>
)
}
}
function mapStateToProps(state) {
return {flash: state.flash.msg}
};
export default connect(mapStateToProps)(PopUp)
Ajoute le composant PopUp dans App.js en bas du code, en dehors du Router.
4 - Affiche une notification pendant une connexion
Dans la quête précédente, lorsque l'utilisateur tentait de se connecter, on utilisait dispatch en lui passant le type d'action "CREATE_SESSION".
Sache que
combineReducers(fonction qui regroupe plusieurs reducers en un seul) va concaténer les reducers. Quanddispatchest appelé, tous les reducers sont sollicités ! Et, par conséquent,action.typeva être présenté dans tous lesswitches/cases. Donc, dans ton cas, si plusieurs reducers implémentent le type d'action"CREATE_SESSION", ils seront tous mis à jour avec l'appeldispatchcorrespondant. En te basant sur ce principe, tu devras afficher une notification via le Snackbar pendant que la connexion est en cours. Attention ! Ne modifie pasSignIn.jsxniPopUp.jsx
5 - La centralisation des actions, ou la fonction MapDispatchToProps
MapDispatchToProps te permet de récupérer les actions qui effectuent le dispatch et de les passer aux props du composant.
6 - Le monde du thunk (fonction intermédiaire qui diffère un traitement, utilisée pour gérer les actions asynchrones)
MapDispatchToProps te permet de récupérer les actions qui effectuent le dispatch et de les passer aux *props du composant.
Challenge
Montre-moi ta propriété
- Tu dois avoir 3 composants/pages
- Tu dois avoir un parcours utilisateur, te permettant d'accéder à toutes les pages
Critères de validation
- Vérifie si les chemins
/,/signin,signupetprofilesont fonctionnels - Vérifie si le navigateur te permet d'accéder à toutes les pages sans modifier manuellement l'URL.
- L'utilisation du bouton back (retour) du navigateur renvoie l'utilisateur en arrière
You were introduced to Redux in the previous quest, but there are still some tricks left to learn before we can consider ourselves masters of the tool.
Goals
- Enable a react application to communicate with the server in an authenticated manner
1 - 1 action, n reducers
It often happens that an action, in a given location of the application, impacts several states. For example, up to now, the Snackbar has been implemented inside a SignIn or Profile container. However, it would, no doubt, be wiser to have a PopUp component that will centrally manage the display. As a consequence, when we are signing in, the action updates the token in the auth reducer, but we also require the msg in the flash reducer.
2 - Delete all Snackbars from your application
Before continuing, delete all of the Snackbar components from your application.
3 - Create a PopUp container
In a PopUp.jsx file, enter the following code:
import React, { Component } from 'react'
import {connect} from 'react-redux'
import Snackbar from 'material-ui/Snackbar';
class PopUp extends Component {
constructor(props) {
super(props);
this.state = {
flash: ""
};
}
componentWillReceiveProps(nextProps){
this.setState({flash: nextProps.flash})
}
handleClose = () => {
this.setState({flash: ""});
};
render() {
return (
<Snackbar
open={this.state.flash !== ""}
message={this.state.flash}
autoHideDuration={2000}
onClose={this.handleClose}
/>
)
}
}
function mapStateToProps(state) {
return {flash: state.flash.msg}
};
export default connect(mapStateToProps)(PopUp)
Add the PopUp component to App.js at the bottom of the code, outside the Router.
4 - Display a notification during a sign-in
In the previous quest, when the user attempted to sign in, we would use dispatch by passing it the "CREATE_SESSION" action type.
You should know that
combineReducerswill concatenate reducers. Whendispatchis called, all the reducers will be requested! And, as a result,action.typeis going to be displayed in all theswitches/cases. So, in your case, if several reducers implement the"CREATE_SESSION"action type, they’ll all be updated with the correspondingdispatchcall. Based on this principle, you’ll have to display a notification via the Snackbar while the sign-in is in progress. Be careful! Don’t modifySignIn.jsxorPopUp.jsx
5 - Action centralisation, or the MapDispatchToProps function
MapDispatchToProps enables you to retrieve actions performing the dispatch and to pass them to the component props.
6 - World of thunk
MapDispatchToProps enables you to retrieve actions performing the dispatch and to pass them to component *props.
Challenge
Show me your property
- You must have 3 components/pages
- You must have a user path, enabling you to access all pages
Validation criterias
- Check if the
/,/signin,signup, andprofilepaths are functional - Check if the browser enables you to access all pages without manually modifying the URL.
- Making use of the browser back button sends the user back