Renaming properties from custom react-query hook

Viewed 728

I made a custom hook with React Query. And I want to rename a value called "data" from React Query to "customUser", so if I have multiple hooks in 1 file I don't have to worry about multiple variables called "data".

Custom Hook

But when I rename the data value to customUser, It won't work.

enter image description here

I don't want all these values, I only want the data value returned and named as customUser enter image description here

2 Answers

react-query will always put exactly in the cache what you return from the queryFn. Since you are using axios, what you are returning is an object with multiple fields, like headers, status, statusText and data. It's the type AxiosResponse, and you are putting all of it in the react-query cache.

Then, react-query will give you all of this in the data field of the result returned from useQuery. That means that useCustomUser().data is actually the AxiosResponse, where your "real data" is also in .data.

So if you rename:

const { data: customUser } = useCustomUser()

customUser.data will have the data you are looking for.

Confusing? Yes, very much so. Which is why many people opt to not store too much in their cache when working with axios by doing something like:

export const fetchUser = () => axios.get(url).then(response => response.data)

only caching the data part of the AxiosResponse, and discarding things like statusText

When accessing the data response that you want to use inside data (before renaming) you access it by using “data.data”. After renaming you simply use “customUser.data”.

Related