Created
January 26, 2024 05:37
-
-
Save dovranJorayev/b268015aee94c63897b7c0bf445ae04f to your computer and use it in GitHub Desktop.
Declarative entity management
This file contains hidden or 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
// shared/api/contracts.ts | |
export type CompanyDetailed = { | |
id: string; | |
name: string; | |
type: 'outcome' | 'income'; | |
notes: string; | |
isLiked: boolean; | |
}; | |
// shared/api/api-company/thunks.ts | |
/** | |
* Here can be any other reactive primitive | |
* like effector, redux, rxjs, mobx etc. | |
*/ | |
export const getComaniesThunk = createAsyncThunk( | |
'companies/get', | |
async () => { | |
const response: CompanyDetailed[] = await getComanies(); | |
return response; | |
} | |
); | |
export const patchCompanyLightThunk = createAsyncThunk( | |
'companies/like-company', | |
async ({ id, ...companyPartial }: { id: number; like: boolean }) => { | |
const response: CompanyDetailed = await patchCompany({ | |
id, | |
...companyPartial | |
}); | |
return response; | |
} | |
); | |
// entities/company.ts | |
export const companiesSlice = createSlice({ | |
name: 'entities/companies', | |
reducers: {...}, | |
extraReducers: builder => { | |
builder.addCase(getComaniesThunk.fulfilled, (state, action) => { | |
state.companies = action.payload; | |
}); | |
builder.addCase(likeComanyThunk.fulfilled, (state, action) => { | |
const { id } = action.payload; | |
const index = state.companies.findIndex(company => company.id === id); | |
state.companies[index] = action.payload; | |
}); | |
} | |
}); | |
// features/manage-company-like.ts | |
export const manageCompanyLikeSlice = createSlice({ | |
name: 'features/manage-company-like', | |
reducers: {...}, | |
extraReducers: builder => { | |
builder.addCase(likeComanyThunk.fulfilled, (state, action) => { | |
// manage internal feature state | |
}); | |
} | |
}); | |
export const manageLikeThunk = createAsyncThunk( | |
'features/manage-company-like', | |
async ({ id, like }: { id: number; like: boolean }) => { | |
const response: CompanyDetailed = await patchCompanyLightThunk({ | |
id, | |
isLiked: like | |
}); | |
return response; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment