Created
May 3, 2021 19:45
-
-
Save technoknol/f2ea26af7b927f65e26691c198eea93a to your computer and use it in GitHub Desktop.
Custom Selector Redux Toolkit with Entity Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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