Consumers
- we try to separate view logic, api logic and form logic by using the concept of consumers
- within the scope of our React projects consumers are hooks which hold pieces of logic which from the same domain
- usage example:
export default function useCommonTagsApiConsumer({selectedWorkspaceId}: Params) {
const [commonTags, setCommonTags] = useState<Tag[]>([]);
const {tagsService} = useUserFeedbackDeps();
const getCommonTags = useCallback(() => {
if (!selectedWorkspaceId) return;
tagsService
.getCommonTags(selectedWorkspaceId, {return_all: true})
.then(({data}) => setCommonTags(data));
}, [selectedWorkspaceId, tagsService]);
useEffect(() => {
(async () => await getCommonTags())();
}, [getCommonTags]);
const addTag = () => {
// ... some logic
};
const deleteTag = () => {
// ... some logic
};
return {commonTags, addTag, deleteTag};
}
export default function SomeComponent() {
const {commonTags, addTag, deleteTag} = useCommonTagsApiConsumer();
return (
<Container>
<InputWithTags
tags={commonTags}
onAddTag={addTag}
onRemoveTag={deleteTag}
/>
</Container>
// ...other UI elements
);
}
- by using this approach our code has better separation of concerns, is more maintainable, and writing tests becomes much easier, since its easy to mock the return value of a consumer