Skip to content

Instantly share code, notes, and snippets.

@technoknol
Created May 3, 2021 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save technoknol/f2ea26af7b927f65e26691c198eea93a to your computer and use it in GitHub Desktop.
Save technoknol/f2ea26af7b927f65e26691c198eea93a to your computer and use it in GitHub Desktop.
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