import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Button } from 'react-bootstrap';
import NavBarManu from './NavBarManu'
const Login = () => {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
function login() {
fetch("http://localhost:3000/login?q=" + name).then((data) => {
data.json().then((resp) => {
console.warn("resp", resp)
if (resp.length > 0) {
localStorage.setItem('login', JSON.stringify(resp))
//Facing error
console.warn(this.props.history.push('list'))
}
else {
alert("Please check username and password")
}
})
})
}
return (
<div>
<br /><h2>Please Login !</h2><br />
<input type="text"
placeholder="enter name"
name="user" onChange={(event) => setName(event.target.value)} /> <br /> <br />
<input
placeholder="enter password"
type="password" name="password" onChange={(event) => setPassword(event.target.value)} /> <br /> <br />
<button onClick={() => { login() }} >Login</button>
</div>
);
};
export default Login;
I am facing error in console.warn(this.props.history.push('list')). The syntax is for class component. That's why it is showing error. I am facing some difficulty in implementing it in functional components. After the user press login button i want the page to be directed towards "list" page. Please help . Give a solution to this. Someone fix this error. If there is any other better way to approach this then do tell .
You are creating functional component and using class component syntax. Your props are empty.
this key word is used in class components to reference to state.
It should be like this:
console.warn(history.push('list'))
You have to import:
import { useHistory } from "react-router-dom";
And in Login component body:
import { useHistory } from "react-router-dom";
const Login = () => {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const history = useHistory()
function login() {
fetch("http://localhost:3000/login?q=" + name).then((data) => {
data.json().then((resp) => {
console.warn("resp", resp)
if (resp.length > 0) {
localStorage.setItem('login', JSON.stringify(resp))
//Facing error
console.warn(history.push('list'))
}
else {
alert("Please check username and password")
}
})
})
}
return ...