Estoy en una aplicacion en la cual se esta configurando el login y logout en ella estoy utilizando context api. Para lo cual el state esta de alguna manera globalizado para que el navbar pueda actualizarse cuando el state pase de false a true. El problema sucede cuando yo refresco el sitio el navbar vuelve a el state previo al login osea false por lo que el state no persiste, he intentado pasar a localstorage el state pero no me ha resultado satisfactorio.
navbar:
// React
import React, { Fragment } from 'react';
// React router
import { BrowserRouter as Router, Switch, Route, Link, withRouter} from 'react-router-dom';
// React apollo
import * as compose from 'lodash.flowright';
// React Components
import LoginPage from '../../views/Login';
import Header from '../../views/Home/Header';
import Home from '../../views/Home';
// React bootstrap
import { Navbar, Form, Nav, NavDropdown, Button, FormControl } from 'react-bootstrap';
import { graphql } from 'react-apollo';
// Mutations
import mutations from './mutations';
// Context
import { Context } from '../../context/context';
class NavbarLayout extends React.Component {
render() {
return(
<Context.Consumer>
{c => {
return(
<Fragment>
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Sample App</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto">
<Nav.Link><Link to="/">Home</Link></Nav.Link>
{localStorage.getItem('isLogged') ?
(
<Fragment>
<Nav.Link onClick={e => c.signOut(e)}>Salir</Nav.Link>
<Nav.Link>Publicar</Nav.Link>
</Fragment>
) :
(
<Nav.Link><Link to="/sign-in">Entrar</Link></Nav.Link>
)}
</Nav>
</Navbar.Collapse>
</Navbar>
<Switch>
<Route path="/home" component={Home} />
<Route path="/sign-in" component={LoginPage} />
</Switch>
</Fragment>
);
}}
</Context.Consumer>
);
}
}
export default compose(
withRouter,
graphql(mutations.signoutUser, { name: 'signoutUser' })
)(NavbarLayout)
context:
// React
import React, { Fragment } from 'react';
// React apollo
import { graphql } from 'react-apollo';
import * as compose from 'lodash.flowright';
// React router
import { withRouter, Redirect } from 'react-router-dom';
// Mutation
import mutations from './mutations';
// Context
export const Context = React.createContext();
class AppProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
// Login & logout states
login_credentials: {},
isLogged: false,
get_data: this.get_data,
submit: this.submit,
signOut: this.signOut
}
}
// Actions
// Login & Logout
get_data = async(e) => {
e.preventDefault();
const { name, value } = e.target;
const data = { [name]: value };
const newData = { ...this.state.login_credentials, ...data };
this.setState({
login_credentials: newData
});
}
submit = async(e) => {
e.preventDefault();
const { signinUser } = this.props;
const { login_credentials } = this.state;
try {
let variables = login_credentials;
const response = await signinUser({variables});
const get_token = response.data.signinUser.token;
// setting localStorage
localStorage.setItem('token', get_token);
this.setState({
isLogged: true
});
localStorage.setItem('isLogged', this.state.isLogged);
this.props.history.push('/');
} catch(error) {
console.log(error);
}
}
signOut = async(e) => {
e.preventDefault();
const { signoutUser } = this.props;
try {
await signoutUser();
localStorage.removeItem('token');
localStorage.removeItem('isLogged');
this.setState({
isLogged: false
});
} catch(error) {
console.log(error);
}
}
// END LOGIN & LOGOUT ACTIONS
render() {
return(
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
export default compose(
withRouter,
graphql(mutations.signinUser, { name: 'signinUser' }),
graphql(mutations.signoutUser, { name: 'signoutUser' })
)(AppProvider)
localStorage
. EstoisLogged: false
debe ser:isLogged: localStorage.getItem('token') || false
.