I am trying to implement a login functionality by following https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/ blog.
I want to persist the user token in local storage.
Everything is working fine, but every time I refresh the page, it throws me an error:
Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.
I have read to fix it clear the site data here Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.
But, I want to have a proper solution or any alternate method to bypass it.
So, that even on the local machine, I can use the login functionality.
Here is what I have tried so far:
For checking if the current user is signed in or not:
const [userState, setUserState] = useState()
useEffect(() => {
const loggedInUser = localStorage.getItem("user");
if (loggedInUser) {
const foundUser = JSON.parse(loggedInUser);
console.log(foundUser);
setUserState(foundUser);
}
}, []);
For login:
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async e => {
e.preventDefault();
const user = { username, password };
const response = await axios.post(
"http://localhost:8000/api-token-auth/",
user
)
props.setUserState(response.data)
const loggedInUser = localStorage.getItem("user");
if (!loggedInUser) {
localStorage.setItem('user', response.data)
}
}