React by Patrik

How to Map Data of React Query

What's the best way to get the data of a promise response of a useQuery() dependant query?

Option 1: you can check if data is available via isSuccess:

const { isSuccess, data } = useQuery(
   ['articles', articleId],
   getArticleById, 
 )

 if (isSuccess) {
    return data.map(...) // <-- data is guaranteed to be defined
 }

Option 2: you can simply check if data exists, or use optional chaining:

const { isSuccess, data } = useQuery(
   ['articles', articleId],
   getArticleById, 
 )
 
 return data?.map(...) ?? null // <-- make sure to handle fallback with ??

Comments

Leave a Comment

All fields are required. Your email address will not be published.