0

tengo el siguiente problema con una aplicacion en la que estoy, estoy en el componente y luego que el usuario ingresa sus credenciales y obtiene la respuesta del servidor (token) el navbar no actualiza a menos que yo lo refresque manualmente, luego del sign in redirige a home ('/').

Estuve intentando pasar los states por props al componente en la funcion sig in, pero sin exito.

        // setting localStorage
        localStorage.setItem('token', get_token);
        this.setState({
            isLogged: true
        });

        this.props.history.push('/');
        "aqui por pathname: '/', state.."

Actualmente mi codigo es el siguiente:

Componente sign in:

    // 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';

    // import mutations
    import mutations from './mutations';

    // React bootstrap
    import { Container, Row, Form, Button } from 'react-bootstrap';

    // Import Style
    import './style.css';

    // Component
    import NavbarLayout from '../Navbar';



    class LoginForm extends React.Component {

        state = {
            login_credentials: {},
            isLogged: false
        }

        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, isLogged } = 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
                });

                this.props.history.push('/');


            } catch(error) {
                console.log(error);
            }


        }


        render() {

            return(
                <Fragment>
                <Container>
                    <Form className="form-container">
                        <h2 className="text-center pb-4">Ingreso</h2>
                        <Form.Group controlId="formBasicEmail">
                            <Form.Control name='email' onChange={e => this.get_data(e)} type="email" placeholder="Email" />
                        </Form.Group>

                        <Form.Group controlId="formBasicPassword">
                            <Form.Control name='password' onChange={e => this.get_data(e)} type="password" placeholder="Contraseña" />
                        </Form.Group>
                        <div className="text-center">
                            <Button className="button-login" variant="primary" onClick={e => this.submit(e)} type="submit">
                                Ingresa
                            </Button>
                        </div>
                    </Form>
                </Container>
                </Fragment>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signinUser, { name: 'signinUser' }),
    )(LoginForm);

componente 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 { Home } from '../../views/Home'; 
    import { LoginPage } from '../../views/Login';

    // React bootstrap
    import { Navbar, Form, Nav, NavDropdown, Button, FormControl } from 'react-bootstrap';
    import { graphql } from 'react-apollo';

    // Mutations
    import mutations from './mutations';


    class NavbarLayout extends React.Component {


        componentDidMount() {

        }


        signOut = async(e) => {
            e.preventDefault();
            const { signoutUser } = this.props;
            try {
                await signoutUser();
                localStorage.removeItem('token');
            } catch(error) {
                console.log(error);
            }
        }


        render() {


            const user_token = localStorage.getItem('token') || '';

            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>
                            {user_token ? (
                                <Fragment>
                                    <Nav.Link onClick={e => this.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="/sign-in" component={LoginPage} />
                    </Switch>

                </Fragment>
            );
        }
    }

    export default compose(
        withRouter,
        graphql(mutations.signoutUser, { name: 'signoutUser' })
    )(NavbarLayout)

1 respuesta 1

0

La respuesta a mi problema fue usar context api de React para poder tener centralizados los states y ademas poder a traves de los consumidores hacer condicionales que me permitan hacer el update del navbar

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/index';

    // 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">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('/home');


                } 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)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.