funtime
funtime

Reputation: 21

How can I access the React useQuery data result?

Currently, when using react query - I can access the response from "data" like...

const { data, error, isLoading } = useQuery(
  'MyQuery',
  () => {
    setNewdata(data)
    return getMyQuery()      
  }
)

then I can .map through the page response like ...

return ({data.data.response.data.map((item) => (...))

Q: Is there way I can shorten the long data.data.response.data list to something shorter like

newdata = data.data.response.data

and then...

{newdata.map((post) => (...)

I do not know where to access -"data" before it is output to the page. Can you help with this?

Thanks for your help in advance

I tried useState to update using setNewdata(data) but it did not show up correctly...

Update: I added async like this below - is it correct?

const { data, error, isLoading } = useQuery(
  'MyQuery',
  async  () => {
    setNewdata(data)
    return await getMyQuery()      
  }
)

If I console.log(data) after useQuery it is populated with the response.

Upvotes: 1

Views: 3117

Answers (2)

Phil
Phil

Reputation: 164733

First, setNewData() has absolutely no place in this code. data is undefined where you're trying to use it. You also do not need to set the data result into local component state; the useQuery hook takes care of state management already.


You can make your query results more opaque by simply transforming the result before returning it.

You can do that either within getMyQuery() or by using a selector in useQuery()

const { data, error, isLoading } = useQuery(["MyQuery"], getMyQuery, {
  select: ({ data }) => data.response.data,
});

return data.map((post) => (
  { /* ... */ }
));

Unnecessary object nesting in API response data is a pet peeve of mine. I highly recommend simplifying the response format if possible.

Upvotes: 1

hamobi
hamobi

Reputation: 8130

whats stopping you from doing..

const { data, error, isLoading } = useQuery(
  'MyQuery',
  async  () => {
    setNewdata(data) // not sure how you set data here before it exists?
    return await getMyQuery() // im assuming this is where the data comes from?   
  }
)
const newdata = data.data.response.data

return ({newdata.map((item) => (...))

Upvotes: 0

Related Questions