I am going through the React-Redux Toolkit tutorials and have set up authentication (partially) - I would like to add a redirect on authentication.
I am using "react-router-dom": "^6.2.1",
In my LoginForm.js I am trying to redirect using Redirect by react-router-dom:
import React, { useState } from "react";
import { Link, Redirect } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { loginUser } from "../../features/auth/authSlice";
export default function LoginForm() {
const dispatch = useDispatch();
const auth = useSelector((state) => state.auth);
const [userInput, setUserInput] = useState({
username: "",
password: "",
});
const onChangeHandler = (e) => {
setUserInput((prevState) => {
return { ...prevState, [e.target.id]: e.target.value };
});
};
const onSubmitHandler = (e) => {
e.preventDefault();
dispatch(loginUser(userInput));
};
if (auth.isAuthenticated) {
return <Redirect to="/" />; // this line of code causes the error
}
Console:
Uncaught (in promise) Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
When I change the code to this it logs true:
if (auth.isAuthenticated) {
console.log(auth.isAuthenticated)
}
I don't understand what the error is saying. Could someone explain it to me so that I may be able to fix this?
EDIT: When I try using the Redirect with no other code in the form it also gives the same error.
I found another post where they used Navigate instead of Redirect. Therefore I changed:
if (auth.isAuthenticated) {
return <Redirect to="/" />;
}
To:
if (auth.isAuthenticated) {
return <Navigate to="/" />;
}
And it started working.