How to pass values to another component on routes?

Asked

Viewed 971 times

0

I have a login page, which authenticates by token and soon after, with the user and password entered are returned the user data. Soon after that I redirect the user to a component called Dashboard. However I wanted to pass the data of it to this 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. There is one condition left 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 but I want to get the data returned from login

import React, { Component } from 'react';

export default class Dashboard extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div></div>
        );
    }
}

1 answer

0

Anderson, I’ve already had to do this once and usually to pass parameters/data to other components we use props or pass to the unstructured data. But in this case in specific authentication, I used Redux where I stored the data in the Redux state and this data is available for other components.

This is the Login class, it 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.