user26607863
user26607863

Reputation: 9

useEffect and dispatch with asyncThunk not working. What am i doing wrong?

In my code below i am using useEffect with dispatch and inside the dispatch function I am using an asyncThunk. If i console.log, in the fulfilled function provided by the thunk, the user then i get the correct data in the payload and in the state.user.

import {Navigate} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {useEffect} from "react";
import {fetchUserData} from "../../redux/slices/authSlice";

const PrivateRoute = ({children}) => {

    const dispatch = useDispatch();

    const {
        user,
        loading,
        error
    } = useSelector((state) => state.auth);

    useEffect(() => {
        dispatch(fetchUserData());
    }, [user, dispatch]);

    console.log(user);
    if (loading) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>Error: {error}</div>;
    }

    return user ? children : <Navigate to="/auth" />;
};

export default PrivateRoute;

The code below is my auth slice

import {createAsyncThunk, createSlice} from '@reduxjs/toolkit';

const authSlice = createSlice({
    name: 'auth',
    initialState: {
        user: null,
        loading: false,
        error: null,
    },
    reducers: {
        logout(state) {
            state.user = null;
        },
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchUserData.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            .addCase(fetchUserData.fulfilled, (state, action) => {
                state.user = action.payload;
                state.loading = false;
            })
            .addCase(fetchUserData.rejected, (state, action) => {
                state.loading = false;
                state.user = null;
                state.error = action.payload || 'Failed to fetch user data';
            });
    },
});

export const fetchUserData = createAsyncThunk('fetchUserData', async (_, thunkAPI) => {
    try {
        const response = await fetch('http://localhost:3000/auth/verifyToken', {
            credentials: 'include',
        });

        if (!response.ok) {
            return thunkAPI.rejectWithValue('Failed to fetch user data');
        }

        return await response.json();
    } catch (error) {
        return thunkAPI.rejectWithValue(error.message);
    }
});

export const authActions = authSlice.actions;
export const authReducer = authSlice.reducer;

I tried using async await inside the useEffect function. I also tried using middleware in the store but i was getting errors. Am i doing anything wrong?

Upvotes: 0

Views: 34

Answers (0)

Related Questions