0

I have a login function like below.

login(){
    var data = {
        client_id: 2,
        client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f',
        grant_type: 'password',
        username: this.state.email,
        password: this.state.password
    }

    fetch('http://127.0.0.1:8000/oauth/token', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then((response) => response.json())
    .then((responseData) => {

        Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now());

        this.props.history.push("/dashboard");
    })
}

I am getting below error.

enter image description here

UPDATE

I read this question and try to use withRouter like below

import React from "react";
import { withRouter } from "react-router-dom";

class Login extends React.Component {
  ...
  login() {
    this.props.history.push("/dashboard");
  }
  ...
}
export default withRouter(Login);

But I am getting below error.

enter image description here

abu abu
  • 6,599
  • 19
  • 74
  • 131

2 Answers2

1

Look at this, if you are using from babel-plugin-transform-decorators, you can use this syntax:

import { withRouter } from 'react-router-dom';

@withRouter
export default class Test extends React.Component {
    login(){
     this.props.history.push('/Dashboard')
  }
}

or you just need to take a look at: withRouter.

0
import React from 'react'
import { withRouter } from 'react-router-dom'

class ShowTheLocation extends React.Component {

    login(){
     ...
     this.props.history.push('/Dashboard')
    }

    render() {
       return (
         <button onClick={this.login}>Dashboard</button>
       )
    }
  }
}

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

When a component is not child of Router, it doesnt have access to history prop. In order to get the history prop, u have to wrap ur component with withRouter HOC.

Gautam Naik
  • 8,990
  • 3
  • 27
  • 42