Search code examples
reactjsreduxreact-hooksreact-reduxredux-toolkit

Redux Toolkit - Best way to capture data from API in our redux store?


I have this question in my mind from past couple of days. What is the best way to capture data from an API in our redux store. I am using redux toolkit.

For e.g below is the code -

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(authUser.pending, state => {
        state.loading = 'pending';
      })
      .addCase(authUser.fulfilled, (state: LoginState, action: PayloadAction<Data>) => {
        state.loading = 'succeeded';
        state.entities.push(action.payload);
      })
  },
});

Like I have created an array, entities and pushed all the data inside it. And if I have to access this data inside my react components, it looks like this -

const role = useSelector((state: RootState) => state?.user?.entities[0]?.roles[0])

Is it fine or is there a better way of doing it. ?


Solution

  • Definitely, there is a better way of doing it. Your current approach is not scalable. Solution to your issue is create selector(*.selectors.ts) files.

    For your above code example, create selector file as: user.selectors.ts:

    import { createSelector } from "@reduxjs/toolkit";
    
    const selectAllUsers = (state) => state.entities;
    
    const selectUserById = (userId) =>
      createSelector(selectAllUsers, (state) =>
        state.find((user) => user.id === userId)
      );
    

    To use the same in your component files:

    const allUsers = useSelector(selectAllUsers); // all users
    const selctedUser = useSelector(selectUserById(9)); // user by id
    

    Hope that answers your question.

    Some useful link:

    1. createSelector
    2. idiomatic-redux-using-reselect-selectors
    3. redux-reducers-selectors

    Thanks