chaining query trees w/o "Rendered more hooks than during the previous render"

Viewed 302

This is an apollo client using the rest link. I have 2 APIs I need to hit, 1 with the value and the id of the record and another api that gives me more information about the record. I then stitch the info together for the content I'm rendering. nope... no gql backend, just trying to get a foot forward and hooking up the client. The way I'm trying to do this is with hooks like

const {data: recordsById = {}, loading: loading1} = useQuery(firstQuery, {variables: {sectionId}})
const records = Object.keys(recordsById).map((recordId) => {
  const {data} = useQuery(secondQuery, {skip: loading1, variables: {sectionId, recordId}})
  return {
    id: recordId,
    value: recordsById[recordId],
    info: data,
  }
})

Obviously when the firstQuery responds with an object like {fooId: 'something', barId: 'else'} there are more useQuery effects in the next render. What's the proper way of doing a sequential query like this w/ apollo?

2 Answers

You can move the second query into a child component. When the first query has finished you render all the child components, they then can use the second query safely (without condition).

React fails because in internals it binds each call of hook to component and order of how it called, it means that in each component hooks call order and number of hooks called should be constant, in your component you should get rid of using hooks in any kind of loops, e.g. with splitting it into separate components

Related