1

I want to display some properties of a JSON object which are in a locally stored JSON file. So, I'm trying like this:

import { DistroList as distroList } from '../backend/distroList.json'

 useEffect(() => {
    
    for(let distro in distroList) {
        if(distroList[distro].Name === distroName) {
            setDistroFeature(distroList[distro])
        }
    }

}, [])

return (
    <div>
        <h1>{distroFeature.Origin}</h1>
    </div>
)

Since the for loop takes time to find the matched object and the component is mounted by then, I'm getting the error as

TypeError: Cannot read property 'Origin' of null

I tried to use fetch API and tried hard to make it asynchronous. I couldn't do it. I want to do something like this:

import { DistroList as distroList } from '../backend/distroList.json'

 useEffect(() => {

    // Fetch the object from distroList.json
    // Update state variable

}, [])

return(
    Display the updated state variable
)

How do I achieve it?

Thanks in advance :)

2
  • Maybe this might work. <h1>{distroFeature?.Origin}</h1> Commented Jun 7, 2021 at 9:14
  • Convert from distroFeature.Origin to distroFeature?.Origin Commented Jun 7, 2021 at 9:14

2 Answers 2

4

One of the following solutions might work for you.

First solution.

<div>
   {distroFeature && <h1>{distroFeature.Origin}</h1>}
</div>

Second solution.

<div>
   <h1>{distroFeature?.Origin}</h1>
</div>
Sign up to request clarification or add additional context in comments.

4 Comments

That works, thanks for the help. But, I'm actually rendering a bunch of properties like distroFeature.Origin in a table. Some of the properties aren't rendering and the <td> will be blank. How can I fix that?
Use a ? with distroFeature wherever you are using it.
A combination of these is working. I have to mention distroFeature in the useEffects() and have a ternary operator in the return. Thank you so much for the help.
I'm glad it helped :)
1

You should add the distroList as a parameter inside your useEffect hook. This way, it will re-run the effect when the value of the distroList is changed (to "not undefined" in this case).

This should work:

import { DistroList as distroList } from '../backend/distroList.json'

 useEffect(() => {
    if (distroList && distroList.length > 0) {
        for(let distro in distroList) {
          if(distroList[distro].Name === distroName) {
              setDistroFeature(distroList[distro])
          }
      }
    }


}, [distroList])

return (
    <div>
        <h1>{distroFeature.Origin}</h1>
    </div>
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.