Created
September 30, 2019 12:01
-
-
Save renanpaiva64/6f21777b4c47b4dffe7f4ee43c5e1485 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react'; | |
| const UsuarioContext = React.createContext({ | |
| usuarioLogado: {}, | |
| doLogin: () => { }, | |
| doLogoff: () => { }, | |
| PersistLogin: () => { }, | |
| RestoreUsuario: () => { } | |
| }); | |
| var cookieName = "HidroUltraApp_"; | |
| var headers = new Headers(); | |
| headers.append('Content-Type', 'application/json'); | |
| var fInit = { | |
| method: 'POST', | |
| headers: headers, | |
| cache: 'default', | |
| mode: 'same-origin', | |
| body: {} | |
| } | |
| export class UsuarioProvider extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| usuarioLogado: {}, | |
| doLogin: this.doLogin, | |
| doLogoff: this.doLogoff, | |
| PersistLogin: this.PersistLogin, | |
| RestoreUsuario: this.RestoreUsuario | |
| }; | |
| } | |
| doLogin = (usuario, senha, path) => { | |
| fInit.body = JSON.stringify({ usuario: usuario, senha: senha }); | |
| fetch("/v1/user/login", fInit) | |
| .then(rest => { | |
| return rest.json(); | |
| }) | |
| .then(d => { | |
| this.setState({ usuarioLogado: d }); | |
| console.log(d, "userdata"); | |
| console.log("usuario logado com sucesso!!!"); | |
| }) | |
| .catch(console.log); | |
| } | |
| PersistLogin = (user) => { this.localStorage.setItem(cookieName, JSON.stringify(user)); }; | |
| RestoreUsuario = () => { | |
| this.setState({ usuarioLogado: JSON.parse(localStorage.getItem(cookieName)) }); | |
| } | |
| doLogoff = () => { this.localStorage.removeItem(cookieName); } | |
| render() { | |
| return ( | |
| <UsuarioContext.Provider value={this.state}> | |
| {this.props.children} | |
| </UsuarioContext.Provider> | |
| ) | |
| } | |
| } | |
| export const UsuarioConsumer = UsuarioContext.Consumer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment