Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Selector Redux Toolkit with Entity Adapter
import { createAsyncThunk, createDraftSafeSelector, createEntityAdapter, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
const socialAccountsAdapter = createEntityAdapter({});
export const getSocialAccounts = createAsyncThunk('app/getSocialAccounts', async () => {
const response = await axios.get(`/SocialAccount/my-connected-accounts`);
// return []
return response.data.data;
});
export const setSocialAccounts = createAsyncThunk('app/setsocialAccounts', async (payload) => {
const response = await axios.post(`/SocialAccount/connect`, payload);
return response.data.data;
});
export const { selectAll: allsocialAccounts } = socialAccountsAdapter.getSelectors(
state => state.scheduler.socialAccounts
);
const customSelectors = (selectState) => {
const selectIds = (state) => state.ids
const selectEntities = (state) => state.entities
const fbConnected = createDraftSafeSelector(
selectIds,
selectEntities,
function (ids, entities) {
return isAccountOfTypeConnected(ids,entities,2);
}
)
const instaConnected = createDraftSafeSelector(
selectIds,
selectEntities,
function (ids, entities) {
return isAccountOfTypeConnected(ids,entities,1);
}
)
const isAccountOfTypeConnected = (ids, entities, type) => {
return ids.some(x => entities[x].platform === type);
};
return {
fbConnected: createDraftSafeSelector(selectState, fbConnected),
instaConnected: createDraftSafeSelector(selectState, instaConnected)
}
}
export const { fbConnected : isFbAccountConnected , instaConnected : isInstaAccountConnected } = customSelectors(state => state.scheduler.socialAccounts)
const socialAccountsSlice = createSlice({
name: 'app/socialAccounts',
// initialState: socialAccountsAdapter.getInitialState({
// socialAccounts: []
// }),
initialState: socialAccountsAdapter.getInitialState(),
reducers: {
},
extraReducers: {
[getSocialAccounts.fulfilled]: socialAccountsAdapter.setAll
}
});
export default socialAccountsSlice.reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment