import { createEntityAdapter, createSelector } from "@reduxjs/toolkit";
import { apiSlice } from './api/apiSlice'
import { IPostUser, IUser } from '../types/entities/IUser'
const adapter = createEntityAdapter({
selectId: (user: IUser) => user.email,
sortComparer: (a: IUser, b: IUser) => a.id - b.id,
})
const initialState = adapter.getInitialState();
export const usersSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
getUsers: builder.query<IUser[], void>({
query: () => '/users',
transformResponse: (users: IUser[]): any => {
return adapter.setAll(initialState, users)
},
providesTags: [{ type: 'Users', id: 'LIST' }]
}),
addUser: builder.mutation<IPostUser, IPostUser>({
query: (user) => ({
url: '/users',
method: 'POST',
body: user
}),
invalidatesTags: [{ type: 'Users', id: 'LIST' }]
}),
updateUser: builder.mutation<IUser, IUser>({
query: (user) => ({
url: `/users/${user.id}`,
method: 'PUT',
body: user
}),
invalidatesTags: [{ type: 'Users', id: 'LIST' }]
}),
deleteUser: builder.mutation<any, number>({
query: (user: number) => ({
url: `/users/${user}`,
method: 'DELETE',
}),
invalidatesTags: [{ type: 'Users', id: 'LIST' }]
}),
})
});
export const {
useGetUsersQuery,
useAddUserMutation,
useUpdateUserMutation,
useDeleteUserMutation
} = usersSlice;
export const selectResult = usersSlice.endpoints.getUsers.select();
const selectData = createSelector(
selectResult,
(result) => result.data
);
export const { selectAll: selectAllUsers, selectById: selectUsersById } = adapter.getSelectors<any>(
(state): any => selectData(state) ?? initialState
);