I am trying to make authentication for a React JS project but, I am getting the following error:
Rendered fewer hooks than expected. This may be caused by an accidental early return statement.
I was reading other questions (like this and this) but I guess my situation is different since I set all the useState
once the component is created.
I have used different approaches to get this done but neither of them worked for me.
I added the methods in the ContextWrapper
component like this:
import React, { useState, useEffect } from "react";
import { useCookies } from "react-cookie";
import jwt from "jsonwebtoken";
import { fetchLogin, fetchVerify } from "../fake-server";
import Context from "./context";
export default ({ children }) => {
const [token, setToken] = useState(null);
const [message, setMessage] = useState(null);
const [loading, setLoading] = useState(false);
const [cookies, setCookie, removeCookie] = useCookies(["token"]);
useEffect(() => {
console.log(cookies);
if (cookies.token) {
setToken(cookies.token);
}
}, []);
useEffect(() => {
if (token) {
setCookie("token", JSON.stringify(token), { path: "/" });
} else {
removeCookie("token");
}
console.log(token);
}, [token]);
function login(email, password) {
fetchLogin(email, password)
/*.then(response => response.json())*/
.then(data => {
const decoded = jwt.decode(data.token);
const token = {
token: data.token,
...decoded
};
setToken(token);
})
.catch(error => {
console.log("error", error);
setMessage({
status: 500,
text: error
});
});
}
function verify() {
fetchVerify(cookies.token)
/*.then(response => response.json())*/
.then(data => {
setToken(data);
})
.catch(error => {
setToken(null);
setMessage({
status: 500,
text: error
});
});
}
function logout() {
setToken(false);
}
const value = {
login,
verify,
logout,
token,
message,
setMessage,
loading,
setLoading
};
return <Context.Provider value={value}>{children}</Context.Provider>;
};
And then this is my Login
component:
import React, { useState, useContext, useEffect } from "react";
import {
Grid,
Card,
Typography,
CardActions,
CardContent,
FormControl,
TextField,
Button
} from "@material-ui/core";
import { Redirect } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
import Context from "../context/context";
const useStyles = makeStyles(theme => ({
root: {
height: "100vh",
display: "flex",
justifyContent: "center",
alignContent: "center"
},
title: {
marginBottom: theme.spacing(2)
},
card: {},
formControl: {
marginBottom: theme.spacing(1)
},
actions: {
display: "flex",
justifyContent: "flex-end"
}
}));
export default ({ history, location }) => {
const context = useContext(Context);
const classes = useStyles();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
if (context.token) {
return <Redirect to="/" />;
}
useEffect(() => {
context.setLoading(false);
}, []);
function onSubmit(e) {
e.preventDefault();
context.login(email, password);
}
return (
<Grid container className={classes.root}>
<Card className={classes.card}>
<form onSubmit={onSubmit}>
<CardContent>
<Typography variant="h4" className={classes.title}>
Login
</Typography>
<FormControl className={classes.formControl} fullWidth>
<TextField
type="text"
variant="outlined"
label="Email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</FormControl>
<FormControl className={classes.formControl} fullWidth>
<TextField
type="password"
variant="outlined"
label="Password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</FormControl>
</CardContent>
<CardActions className={classes.actions}>
<Button type="submit" variant="contained" color="secondary">
Login
</Button>
</CardActions>
</form>
</Card>
</Grid>
);
};
Here I created this sandbox to reproduce the error that happens when login()
method is triggered. So, what am I doing wrong?
return <Redirect to="/" />;
before theuseEffect
in Login is the problem. – Antepenult