-
Hi ✋ How can I use useSWR with a service layer? Example: // service layer
export const getData = async (id, params = { orderBy: 'created_at', order: 'DESC' }) => {
const response = await apiGet(`entity/${id}/resource`, params); // custom fetching layer
return response.data;
};
// component
const Component = ({ initialData }) => {
const { data } = useSWR(null, () => getData(id, { orderBy, order }, { initialData });
// ...
}); Can I use the hook without declaring a key and then passing all the parameters through the function? I really don't want to pass the hardcoded endpoint on all the components that need it, so calling the hook without declaring the key must be very useful for me. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I do this, but you should pass params as part of the key (note the key can be anything except an object) not only a string with a URL useSWR(["data", id, orderBy, order], (key, id, orderBy, order) => getData(id, { orderBy, order }), { initialData }) Also note if you use null as key SWR will not call your fetcher function. |
Beta Was this translation helpful? Give feedback.
-
Thanks! That was very helpful to me! 🙂 |
Beta Was this translation helpful? Give feedback.
I do this, but you should pass params as part of the key (note the key can be anything except an object) not only a string with a URL
Also note if you use null as key SWR will not call your fetcher function.