0

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.

  • 1
    [optional-chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? You could also show a spinner while data is being fetched from the backend. – Yousaf Oct 15 '20 at 10:56
  • @Yousaf - are you able to optional-chain in a way so that you can use destructuring? I pass props into the component with destructuring so how would you approach that? – Mitchell Cartwright Oct 15 '20 at 11:00
  • If you destructure an undefined property from an object, value of the destructured property name will be undefined, you won't get an error. – Yousaf Oct 15 '20 at 11:03
  • Howcome `project` is undefined? do projects contain null or undefined entities? If yes, what about filtering? e.g. map(project => project ? : null) – Kunukn Oct 15 '20 at 11:05

0 Answers0