0

How i can use the the useHistory function inside my class based component? I need to redirect my user to a certain page after the login, passing also the state class as an attribute.

enter image description here

The function onSubmit will execute after the login form submit.


    import React from "react";
    import LoginButton from "../../atoms/AuthenticationButton";
    import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom";
    import axios from "axios";
    import $ from 'jquery'

    class Login extends React.Component {
        state = {
            username: '',
            password: '',
            key: '',
            authenticated: false
        };

    onSubmit = (e) => {
        e.preventDefault();
        let navigate = useNavigate();
        $('#errorMessage').html(
            ""
        )
        axios.post('http://127.0.0.1:8000/api/dj-rest-auth/login/', {
            username: this.state.username,
            password: this.state.password
        }).then((response) => {
            this.setState({ key: response.data.key });
            this.setState({ authenticated: true })
            console.log(this.state);
            console.log(response);
            navigate('/dashboard', { replace: true })


        }).catch((error) => {
            if (error.response) {
                for (var field in error.response.data) {
                    for (var errore in field) {
                        if (typeof error.response.data[field][errore] === "string") {
                            $('#errorMessage').append(
                                "<div class='alert alert-secondary' role='alert'>" + error.response.data[field][errore] + "</div>"
                            )
                        }
                    }


                }

            }
        })


    }
    render() {
        return (
            <>
                <form>
                    {/* {'{'}#    username or number field      #{'}'} */}
                    <div className="row" style={{ marginTop: '5%' }}>
                        <div className="col-lg-3" />
                        <div className="col-lg-6">
                            <input type="email"
                                className="form-control input-background-color"
                                id="inputEmail"
                                placeholder="Email or Username"
                                value={this.state.username}
                                onChange={(e) => this.setState({ username: e.target.value })}
                            />
                        </div>
                        <div className="col-lg-3" />
                    </div>

                    {/* {'{'}#    password field      #{'}'} */}
                    <div className="row" style={{ marginTop: '3%' }}>
                        <div className="col-lg-3" />
                        <div className="col-lg-6">
                            <input
                                type="password"
                                className="form-control input-background-color"
                                id="inputPassword3"
                                placeholder="Password"
                                value={this.state.password}
                                onChange={(e) => this.setState({ password: e.target.value })}
                            />
                        </div>
                        <div className="col-lg-3" />
                    </div>

                    {/* errori da back end o front end */}
                    <div className="col-12 margin-top-5" >
                        <div className="row">
                            <div className="col-2"></div>
                            <div id="errorMessage" className="col-8"></div>
                            <div className="col-2"></div>
                        </div>
                    </div>

                    {/* {'{'}#  FORGOT PASSWORD   #{'}'} */}
                    <div className="row" style={{ marginTop: '3%' }}>
                        <div className="col-lg-3" />
                        <div className="col-lg-6">
                            <a href="/" style={{ color: 'red', fontSize: '13px' }}>Forgot Password?</a>
                        </div>
                        <div className="col-lg-3" />
                    </div>

                    {/* {'{'}#    LOGIN SUBMIT BUTTON   #{'}'} */}
                    <LoginButton onClick={this.onSubmit} text="Login" marginTop="5%" />
                </form>
            </>
        )
    }
}

export default Login

After the .then in the axios request i want redirect the user that has correctly log on to the /dashboard page.

1 Answers1

0

I have not worked with class based components but I know that you should not create an instance of a hook inside a function. So try writing line no.17 either on line no.6 or line no. 14. If nothing works, so for the workaround you can use

window.location.href

https://www.geeksforgeeks.org/how-to-redirect-to-a-relative-url-in-javascript/