How to pass values to another component in the routes?

0

I have a login page, which does authentication by token and shortly after, with the user and password entered are returned the user data. Right after this I redirect the user to a component called Dashboard. But I wanted to pass his data to that component.

Index.js Here I have my routes created

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import Sobre from './Sobre.js';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Dashboard from './ui/Dashboard';
import LoginForm from './ui/LoginForm';

ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route path="/" exact={true} component={LoginForm} />
            <Route path="/sobre" component={Sobre} />
            <Route path="/dashboard" component={Dashboard} />
        </Switch>
    </BrowserRouter>
     ,document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.register();

Login page

In the isUser function it is redirected to Dashboard. It is missing a condition if it is user or not yet, but this is not the case.

import React, { Component } from 'react';


export default class LoginForm extends Component{

    constructor(){
        super();

        this.state = {
            login: '',
            senha: '',
            authenticate_code: '',
            url: 'http://192.168.0.19/api/'         
        };

        this.handleLogin = this.handleLogin.bind(this);
        this.isUser = this.isUser.bind(this);
    }

    handleLogin(e){

        e.preventDefault();

        let dataToGetToken= {
            nome: "teste",
            senha: "1234"
        };

        try{
            fetch(this.state.url + 'token', {
              method: 'POST',
              body: JSON.stringify(dataToGetToken),
              headers: {
                "Content-type": "application/json; charset=UTF-8"
              } 
            })
            .then(response => response.json())
            .then(json => { 
                this.setState({ authenticate_code: 'bearer ' + json.token })
                this.isUser(this.refs.login.value, this.refs.pass.value, this.state.authenticate_code);
            });
        }
        catch(e){
          console.log(e);
        }

    }

    isUser(name, pass, token){

        var login = new Object();
        login.nome = name;
        login.senha = pass;
        console.log(login);
        console.log(token);
        try{
            fetch(this.state.url + 'usuarios/getuser', {
              method: 'POST',
              body: JSON.stringify(login),
              headers: {
                "Authorization": token,
                "Content-type": "application/json; charset=UTF-8"
              } 
            })
            .then(response => response.json())
            .then(json => { 
                //Redireciona
                this.props.history.push('/ui/Dashboard')
            });
        }
        catch(e){
          console.log(e);
        }

    }

    render(){
        return(
            <div className="App">
                <div className="container">
                    <div className="row">
                        <div className="col-sm-12">
                            <form onSubmit={this.handleLogin}>
                                  <div className="form-group">
                                    <label htmlFor="exampleInputEmail1">Login</label>
                                    <input type="text" ref="login" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"/>
                                    <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
                                  </div>
                                  <div className="form-group">
                                    <label htmlFor="exampleInputPassword1">Senha</label>
                                    <input type="password" ref="pass" className="form-control" id="exampleInputPassword1" placeholder="Password" />
                                  </div>
                                  <div className="form-group form-check">
                                    <input type="checkbox" className="form-check-input" id="exampleCheck1" />
                                    <label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
                                  </div>
                                  <button type="submit" className="btn btn-primary">Submit</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            );
    }
}

I want to redirect to this component however I want to get the data returned from the login

import React, { Component } from 'react';

export default class Dashboard extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div></div>
        );
    }
}
    
asked by anonymous 08.10.2018 / 17:26

1 answer

0

Anderson, I've had to do this once and usually to pass parameters / data to other components we use the props or we go through the unstructured data. But in this specific case of authentication, I used Redux where I stored the data in the state of Redux and this data becomes available to other components.

This is the Login class, looks like this:

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  login = () => {
    const { username, password } = this.state;
    const data = {};
    data.client_id = Config.CLIENT_ID;
    data.client_secret = Config.CLIENT_SECRET;
    data.grant_type = 'password';
    data.username = username;
    data.password = password;
    data.scope = '';
    const { ...props } = this.props;
    props.onLogin(data);
  };

  verificaToken = () => {
    if (localStorage.str_storage_tk) {
      Config.TOKEN = JSON.parse(localStorage.str_storage_tk);
      Config.AUTH_TYPE = 'Bearer ';
    }
  };

  render() {
    if (isAuthenticated()) {
      return <Redirect to="/perfil" />;
    }
    const { ...props } = this.props;
    return (
      <Loadable
        active={props.isLoading}
        spinner
        background="rgba(245,245,245, 0.7)"
        color="#000"
        text="Aguarde..."
        spinnerSize="115px"
      >
       Implementação do HTML
      </Loadable>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  onLogin: data => dispatch(login(data)),
});

const mapStateToProps = state => ({
  isLoading: state.ui.isLoading,
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Login);
    
22.11.2018 / 10:23