'How to apply createEntityAdapter to createApi slice

I have implemented successfully a redux-toolkit api. Now Im trying to use createEntityAdapter to be able to use the pre-built selector methods.

import {
  createEntityAdapter,
  createSelector,
} from '@reduxjs/toolkit'
import api from '@app/redux/reducers/api'

const environmentsAdapter = createEntityAdapter()
const initialState = environmentsAdapter.getInitialState()

export const extendedApiSlice = api.injectEndpoints({
  endpoints: (builder) => ({
    getEnvironments: builder.query({
      query: ROUTES.ENVIRONMENTS,
      // IMPORTANT
      transformResponse: (responseData: any) => {
        return environmentsAdapter.setAll(environmentsAdapter.getInitialState(), responseData)
      },
    }),
  }),
})

// Default api slice hooks
export const {
  useGetEnvironmentsQuery, // data returns the normalized data correctly
  usePostEnvironmentMutation
} = extendedApiSlice

export const selectEnvironmentsResult = extendedApiSlice.endpoints.getEnvironments.select()

const selectEnvironmentResultData = createSelector(
  selectEnvironmentsResult,
    environmentResult => {
    console.log(environmentResult) // {status: "uninitialized", isUninitialized: true, isLoading: false, isSuccess: false, isError: false}
    return environmentResult?.data ?? []
  }
)

export const {
  selectAll: selectAllEnvironments, // returns an empty array, ERROR!
} = environmentsAdapter.getSelectors(state => {
  console.log( state ) // Here the entire redux state is printed, ERROR?
  return selectEnvironmentResultData(state) ?? initialState
})

When using useGetEnvironmentsQuery hooks, I get the data correctly. But when I use selectAllEnvironments I get an empty array. Why?



Solution 1:[1]

The problem solved changing the arguments of useGetEnvironmentsQuery. I replaced:

  const { isLoading, isFetching, error } = useGetEnvironmentsQuery({}) // WITH EMPTY OBJECT
  const data = useSelector(selectAllEnvironments)
  console.log( data ) // empty array

to:

  const { isLoading, isFetching, error } = useGetEnvironmentsQuery() // WITH NO ARGS
  const data = useSelector(selectAllEnvironments)
  console.log( data ) // data is defined here finally :)

Not sure whats going on exactly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rashomon