I have a div in which I map through an array and return components with rendered results. For each array value I do an API call, multiple checks, and calculations, and, if the calculations are correct, I return the final JSX, if not, I return nothing.
The main component look like this:
export const FinalComponent = ({ items }) => {
return (
<div>
{items.map((item) => (
<ItemComponent data={item} />
))}
<div>
);
};
The Item component looks like this:
export default function ItemComponent({ data }) {
const [returnedItem, setReturnedItem] = useState(null);
// API CALL SETS returnedItem
// Necessary checks and calculations
// If check length is more then 0, return component
if (check > 0) {
return (
<div>
<p>{returnedItem.name}</p>
</div>
);
}
}
This works as it should. The problem is, let’s say in the "items" array I have 3 items and I go through each of them, but none of them goes through check and in the end, I return nothing. What I want, is if that scenario happens I want to show one message "Data not found". How can I wait for all .map items to finish and check the final .map array if there is no returned component in there?
2
Answers
I think what you could do is follow the "Presentational and Container Component pattern" as described in this article by Dan Abramov
Personally, I’d keep
ItemComponent
as a presentational component, and keepFinalComponent
as a container component.Inside
FinalComponent
Id do all the calculations for all of the data, and stick the result in an array of finalised data. Then you could dodata.map
on the already calculated data – that wayItemComponent
could receive just the data to display.You can pass a function to your child component
ItemComponent
which marks a state of the parent componentFinalComponent
as true if some children have ‘check’ greater than 0. Then, you can check if that state is not marked as true to render "Data not found".