No page rendered after successful login stuck on same screen
Unanswered
Blue horntail woodwasp posted this in #help-forum
Blue horntail woodwaspOP
Problem: dispatch doesn't update directly after clicking login. after a refresh in seems to update
here is the whole code: https://github.com/Redclawww/MoonDevs-Assignment
here is the whole code: https://github.com/Redclawww/MoonDevs-Assignment
6 Replies
Blue horntail woodwaspOP
const HomePage = () => {
const dispatch = useAppDispatch();
const { user, logoutUser } = useAuthSession();
const onSubmit: SubmitHandler<Inputs> = async (data) => {
const {username, password} = data;
try {
const response = await fetch('/api/login', {
body: JSON.stringify({ username,password }),
});
if (response.ok) {
const { token,user } = await response.json();
localStorage.setItem('token', token);
dispatch(setToken(token));
dispatch(setUser(user));code reduced to fit
const useAuthSession = () => {
const dispatch = useAppDispatch();
const user = useAppSelector((state: RootState) => state.auth.user);
const { toast } = useToast()
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
fetch('/api/user', {
headers: {
Authorization: `Bearer ${token}`,
},
}).then((res) => res.json())
.then((userData) => {
dispatch(setUser(userData));
})
.catch((error) => {
console.error('Error fetching user data:', error);
dispatch(clearAuth());
});
}
}, [dispatch]);
const logoutUser = () => {
localStorage.removeItem('token');
dispatch(clearAuth());
toast({
title: 'Logged out',
description: "You have been successfully logged out",
})
};
return { user, logoutUser };
};
export default useAuthSession;store: import { configureStore } from "@reduxjs/toolkit";
import { useDispatch, useSelector } from "react-redux";
import { TypedUseSelectorHook } from "react-redux";
// import authReducer from 'lib/redux/auth/auth.slice';
import authReducer from "./auth/auth.slice";
const store = configureStore({
reducer: {
auth: authReducer,
},
});
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch<AppDispatch>;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
export default store;useAuthSeassions:
Blue horntail woodwaspOP
please some one help 😔