Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. import React from 'react';
  2.  
  3. const UsuarioContext = React.createContext({
  4. usuarioLogado: {},
  5. doLogin: () => { },
  6. doLogoff: () => { },
  7. PersistLogin: () => { },
  8. RestoreUsuario: () => { }
  9. });
  10.  
  11. var cookieName = "HidroUltraApp_";
  12. var headers = new Headers();
  13. headers.append('Content-Type', 'application/json');
  14.  
  15. var fInit = {
  16. method: 'POST',
  17. headers: headers,
  18. cache: 'default',
  19. mode: 'same-origin',
  20. body: {}
  21. }
  22. export class UsuarioProvider extends React.Component {
  23.  
  24. constructor(props) {
  25. super(props);
  26. this.state = {
  27. usuarioLogado: {},
  28. doLogin: this.doLogin,
  29. doLogoff: this.doLogoff,
  30. PersistLogin: this.PersistLogin,
  31. RestoreUsuario: this.RestoreUsuario
  32. };
  33. }
  34. doLogin = (usuario, senha, path) => {
  35. fInit.body = JSON.stringify({ usuario: usuario, senha: senha });
  36. fetch("/v1/user/login", fInit)
  37. .then(rest => {
  38. return rest.json();
  39. })
  40. .then(d => {
  41. this.setState({ usuarioLogado: d });
  42. console.log(d, "userdata");
  43. console.log("usuario logado com sucesso!!!");
  44. })
  45. .catch(console.log);
  46. }
  47.  
  48. PersistLogin = (user) => { this.localStorage.setItem(cookieName, JSON.stringify(user)); };
  49.  
  50. RestoreUsuario = () => {
  51. this.setState({ usuarioLogado: JSON.parse(localStorage.getItem(cookieName)) });
  52. }
  53.  
  54. doLogoff = () => { this.localStorage.removeItem(cookieName); }
  55.  
  56. render() {
  57. return (
  58. <UsuarioContext.Provider value={this.state}>
  59. {this.props.children}
  60. </UsuarioContext.Provider>
  61. )
  62. }
  63. }
  64.  
  65. export const UsuarioConsumer = UsuarioContext.Consumer;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement