usersSliceRtk.js

    0

    0

    This code creates an extended API Slice object that will provide endpoints for getting users.

    The first thing this code does is get an initial state for the users adapter using the getInitialState() method. Then it creates a selector using the createSelector() function. The selectUsersResult selector will generate a data object for a request that returns users. The selectUsersData() function will create a selector that will return the data object for a request that returns users by ID. Finally, it creates two getters using the getSelectors() function. The first getter will get the state for the users adapter and the second getter will get the data object for a request that returns users by ID.

    import { createEntityAdapter, createSelector } from '@reduxjs/toolkit'
    
    import { apiSlice } from '../api/apiSlice'
    
    const usersAdapter = createEntityAdapter()
    
    const initialState = usersAdapter.getInitialState()
    
    export const extendedApiSlice = apiSlice.injectEndpoints({
      endpoints: (builder) => ({
        getUsers: builder.query({
          query: () => '/users',
          transformResponse: (res) => {
            return usersAdapter.setAll(initialState, res)
          },
        }),
      }),
    })
    
    export const { useGetUsersQuery } = extendedApiSlice
    
    // Calling `someEndpoint.select(someArg)` generates a new selector that will return
    // the query result object for a query with those parameters.
    // To generate a selector for a specific query argument, call `select(theQueryArg)`.
    // In this case, the users query has no params, so we don't pass anything to select()
    export const selectUsersResult = extendedApiSlice.endpoints.getUsers.select()
    
    const selectUsersData = createSelector(
      selectUsersResult,
      (usersResult) => usersResult.data
    )
    
    export const {
      selectAll: selectAllUsers,
      selectById: selectUserById,
    } = usersAdapter.getSelectors((state) => selectUsersData(state) ?? initialState)
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.