i've been trying how to make my query system work but i don't know how.
Im using React D3 Tree, im fetching 4 queryes from Apollo Graphql:
-enterprises -factories -areas -nodes
each one is dependant, for example factories need enterprise id to fetch or areas need factory id.
This is the code i have at the moment
// Query Calls
const { data: enterprises } = useQuery(getEnterprises);
const { data: factories } = useQuery(getFactories, {
variables: {
"enterprise_id": enterprises?.enterprises[0].id,
},
skip: !enterprises || !enterprises.enterprises || enterprises.enterprises.length === 0,
});
const { data: areas, } = useQuery(getAreas, {
variables: {
"factory_id": factories?.factories[0].id,
},
skip: !factories || !factories.factories || factories.factories.length === 0,
});
const { data: nodes, loading: loading2 } = useQuery(getNodes, {
variables: {
"area_id": areas?.areas[0].id,
},
skip: !areas || !areas.areas || areas.areas.length === 0,
});
This aproach works but im only fetching the first of each and i want to fetch all data, i tried to use functions that return mapped queries but throws error because the argument is undefined.
Any help will be apreciated
It seems that you are not leveraging graphql given possibilities. This issue would be best fixed on the backend, sou you can query related objects recursively within one query.
type Factory {
id: ID!
area: Area
etc...
}
type Area {
id: ID!
factory_id: ID
nodes: [Node]
etc...
}
type Node{
id: ID!
area_id: ID
etc...
}
But maybe a solution to your problem could be to use queries which return a list of objects and you can use an array of ids as variable. Then you could do something like this:
const { data: areas, } = useQuery(getAreas, {
variables: {
"factory_ids": factories?.factories?.map(({id})=>id),
},
skip: !factories || !factories.factories || factories.factories.length === 0,
});