useMethod
Useful for async services, it returns the state of the promise and executes automatically when the component where it is encapsulated first renders
It is similar to the react-query
and apollo-graphql
hooks behavior
but since the complete async logic will be encapsulated in one service method, no need to listen in a useEffect or a useMemo a query to finish, the useMethod just wraps a complete use case and generates the data useful for the UI (in most of the cases no need to store a isLoading boolean in the store)
export const ShoesComponent = () => {
const shoesService = useService('shoes')
const {
isLoading,
isError,
isSuccess,
isCalled,
error,
call,
data,
} = useMethod(shoesService.load)
if (!isCalled || !isLoading) {
return <Loader>
}
if (isError) {
return <span>An error occured</span>
}
return <Shoes data={data}>
}
It can also be used in one line by using the method string
export const ShoesComponent = () => {
const {
isLoading,
isError,
isSuccess,
isCalled,
error,
call,
data,
} = useMethod('shoes.load')
...
}