0

I am trying to auth session by random user with http get request and createAsyncThunk. fetching the user data in App.js on mount hook. I can see the get request in my network and the new fetched state in redux dev tool, but my TopBar.js useSelector return the initial state before the fetch.

TopBar.js user log:

enter image description here

App.js:

  const dispatch = useDispatch();

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

authSlice.js:

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

const initialState = {
  isLoggedIn: true,
  user: {},
  loading: false,
  error: null,
};

export const fetchRandomUserData = createAsyncThunk(
  'auth/fetchRandomUser',
  async () => {
    try {
      const response = await fetch('https://randomuser.me/api/');
      const data = await response.json();
      return data.results[0];
    } catch (error) {
      throw Error(error);
    }
  }
);

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout(state, action) {
      state.isLoggedIn = false;
    },
  },
  extraReducers: {
    [fetchRandomUserData.pending]: (state, action) => {
      state.loading = true;
      state.error = null;
    },
    [fetchRandomUserData.fulfilled]: (state, action) => {
      console.log("action.payload",action.payload);
      state.user = action.payload;
      state.loading = false;
    },
    [fetchRandomUserData.rejected]: (state, action) => {
      state.error = action.error.message;
      state.loading = false;
    },
  },
});

export const { logout } = authSlice.actions;

export default authSlice.reducer;


store.js

import { configureStore } from '@reduxjs/toolkit';
// import booksReducer from './reducers/booksReducer';
import booksReducer from './slices/bookSlice';
import authReducer from './slices/authSlice';

const store = configureStore({
  reducer: { books: booksReducer, auth: authReducer },
});

export default store;

TopBat.js:

export default function TopBar(): JSX.Element {

 
  const user = useSelector((state: any) => state.auth);
  console.log("topbar",user); // returns the initial state





//....
  
Sergey Arenzon
  • 325
  • 4
  • 17
  • 1
    Are you maybe using React 18 with react-redux 7, or is this in a Firefox where a pop-up is opened (known React bug)? – phry Jun 25 '22 at 17:20
  • Yes it is react 18 with redux 7 but I use chrome, my problem is that my components renders before thunk finish its fetching. – Sergey Arenzon Jun 25 '22 at 19:11
  • 1
    Those are two different problems, so with RR7 and R18, you are fulfilling one of the problem scenarios. – phry Jun 26 '22 at 06:44

1 Answers1

1

Please make sure that you update react-redux to version 8 if you are using react 18. There are known cases where components just stop updating if you are using react-redux 7 and lower with react 18.

phry
  • 35,762
  • 5
  • 67
  • 81