I am using useContext to fetch documents from MongoDB.
I know that there is some amount of time that it takes for my app to fetch the data, save it to state and then pass the context to children.
My question is - how do I handle the time inbetween fetching and rendering without having errors throw.
Here is some sample code where projects
is the data coming from useContext
:
PARENT
<Container>
<div className={classes.cardsContainer}>
{projects.length > 0 && projects.map((project) => <ProjectCard key={project._id} project={project} />)}
</div>
</Container>
I map over projects
and pass each of these as a prop to <ProjectCard />
.
However in the child if I try and render project.projectName
(this is a property in the object) in the child.
If I console.log(project.projectName)
in the children I get the error TypeError: Cannot read property 'projectName' of undefined
.
I know I can solve this by using project && project.projectName
however is there a better way to do this?
There must be a more elegant way to do this so I don't have object && object.property
everytime I want to use context.