1

When we get data from useQuery hook, I need to parse the data a specific type before it return to user. I want data which return from useQuery hook should be of "MyType" using the parsing function i created below. I am unable to find method to use my parsing function. Is there any way to do it? I don't want to rely on schema structure for data type.

type MyType = {
id: number;
//some more properties
}

function parseData(arr: any[]): MyType[]{
  return arr.map((obj, index)=>{
    return {
      id: arr.id,
      //some more properties
    }
  })
}

const {data} = await useQuery('fetchMyData', async ()=>{
    return await axios.get('https://fake-domain.com')
  }
)

2 Answers 2

4

I would take the response from the api and transform it inside the queryFn, before you return it to react-query. Whatever you return winds up in the query cache, so:

const { data } = await useQuery('fetchMyData', async () => {
    const response = await axios.get('https://fake-domain.com')
    return parseData(response.data)
  }
)

data returned from useQuery should then be of type MyType[] | undefined

There are a bunch of other options to do data transformation as well, and I've written about them here:

https://tkdodo.eu/blog/react-query-data-transformations

Sign up to request clarification or add additional context in comments.

Comments

0

I think you should create your own hook and perform normalisation there:

const useParseData = () => {
 const { data } = await useQuery('fetchMyData', async () => {
    return await axios.get('https://fake-domain.com')
 }
 
 return parseData(data)  
}

And where you need this data you could just call const parsedData = useParseData()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.