redux-persist icon indicating copy to clipboard operation
redux-persist copied to clipboard

Stuck and strange state with redux-persist

Open ciolo opened this issue 3 years ago • 0 comments

Hi guys, I have a problem with redux-persist. This is my authentication slice:

const initialState: AuthState = {
  isLoading: false,
  isLoggedIn: false,
  username: '',
  token: '',
  role: '',
  authenticationError: '',
};

export const login = createAsyncThunk(
  'auth/login',
  async (credentials: Credentials, thunkAPI) => {
    try {
      const response = await signIn(credentials);
      return {
        username: response.data.user,
        token: response.data.token,
        role: response.data.typeUser,
      };
    } catch (error) {
      console.log(error);
      return thunkAPI.rejectWithValue({error: error.message});
    }
  },
);

export const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(login.pending, state => {
        state.isLoading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.username = action.payload.username;
        state.role = action.payload.role;
        state.token = action.payload.token;
        state.isLoggedIn = true;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.isLoggedIn = false;
        if (action.error.message) {
          state.authenticationError = action.error.message;
        }
      });
  },
});

export const selectAuth = (state: RootState) => state.auth;

export default authSlice.reducer;

This is my store.ts, App.tsx and Router.tsx respectively:

const reducers = combineReducers({
  auth: authReducer,
  dishes: dishesReducer,
  courses: coursesReducer,
});

const persistConfig = {
  key: 'root',
  version: 1,
  storage: AsyncStorage,
};

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
  //devTools: process.env.NODE_ENV !== 'production',
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;
let persistor = persistStore(store);

  return (
    <PaperProvider theme={theme}>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <Router />
        </PersistGate>
      </Provider>
    </PaperProvider>
  );
export const Router = () => {
  const auth = useAppSelector(selectAuth);


  if (auth.isLoading) {
    return <Loading />;
  }
  return (
    <NavigationContainer>
      {auth.isLoggedIn ? (
        <Drawer.Navigator
          initialRouteName="Home"
          drawerContent={props => <DrawerContent {...props} />}>
          <Drawer.Screen
            options={{headerShown: false}}
            name="HomeDrawer"
            component={AppStack}
          />
        </Drawer.Navigator>
      ) : (
        <AuthStack />
      )}
    </NavigationContainer>
  );
};

As you can see in img below, when I run the app it starts with loading component, because auth.isLoading is true. In initial state is set to false. It should not be to false when the app starts? Without redux-persist works fine, the app starts with login screen etc. Where or what am I wrong? Screenshot 2022-01-26 at 08 05 58

ciolo avatar Jan 26 '22 07:01 ciolo