I have a list of components which have to fetch their own data and render childs based on the fetched data. How can I show a FallbackComponent as child of the top component if all of the child components (ComponentAs) don't have any own childs?
Example:
ContainerComponent
FallbackComponent // should only render if there is not a single ComponentB in any ComponentA
FallbackComponent2 // Renders if there is no ComponentA
// Below should only render if there is atleast one ComponentB
ComponentA // fetches own data - to render some ComponentB
ComponentB
ComponentB
ComponentB
ComponentA // fetches own data - to render some ComponentB
ComponentB
ComponentB
ComponentA // fetches own data - to render some ComponentB
ComponentB
ComponentB
ComponentB
ComponentA // fetches own data - to render some ComponentB
ComponentB
ComponentB
I already tried to listen for childNodes on ContainerComponent which counts the number of ComponentB's but according to React Doc this is not recommend and it also doesn't work because the data will update quite often. Also I tried to pass the number of each results from ComponentA up to the ContainerComponent to render the Fallback if results === 0 but in this case the results length from one ComponentA overwrites the results length of another.
The way i see it is that your container should be aware when a componentA data is done being fetched & if it has rendered a component. Each ComponentA could have a props "onSuccess" From the container Component that will return the number of component rendered
ContainerComponent
const [components, setComponents] = [{cName: "", nbChildren: 0}]
onSuccess = (componentName, nbChildrenRendered) => {
newComponentList = new Set([...components, {cName: componentName, nbChildren: nbChildrenRendered}])
setComponents(newComponentList)
}
<ComponentA onSuccess={onSuccess} />
ComponentA :
const fetchData = () => {
/... Your implementation */
onSuccess("myComponent", data.structureYouLoopOnToRenderYourChildren.length)
}
Then its just a matter to check inside your component state if the nbOfChildren for a specific component is valid according to your criterias or not