0

I am new to REACT and trying to use array.find function. Getting error Cannot read property first_name of undefined. When I declare JSON array inside RenderIt function. Not sure, why REACT cannot see results array.

export default function App() {

  const [results, SetResults] = useState([])
  useEffect(() => {
    const JSON = [{
        EMPLID: '345386',
        first_name: 'David',
      },
      {
        EMPLID: '345397',
        first_name: 'Luca',
      },
    ]
    SetfName(JSON[0].first_name)
    SetResults(JSON)
  }, [])

  const RenderIt = () => {
    let found = results.find(element => element.EMPLID === '345397')
    return ( < div > {
        found.first_name
      } < /div>)
    }

    return ( <
      div className = "App" >
      <
      h1 > First Name < /h1> <
      h2 > {
        (RenderIt())
      } < /h2>       <
      /div>
    );
  }
1
  • Is SetfName a typo? Commented Jul 24, 2020 at 21:11

2 Answers 2

1

The function provided to useEffect only runs after the first render, so during that first render, results is [], so the find can't find anything and returns undefined, which in turn means that found is undefined, and thus doesn't have the first_name property, which is the error you're seeing.

You want to check whether results has anything, and the only optionally render the RenderIt stuff if so.

Put this at the bottom inside your h2:

{ results !== [] && RenderIt() }

Or you can change RenderIt to:

const RenderIt = () => {
    let found = results.find(element => element.EMPLID === '345397')
    if (!found) return '';
    return (<div> {found.first_name} </div>)
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Luke. I tried this and getting same error message. { results !== [] && RenderIt() } Still not clear, the order of execution. If I use results.map inside RenderIt(), it works fine. However, if I use results.find it does not.
try the second solution
Luke Storry, the second solution worked. Thanks for taking time and responding. So, is this right order of execution? 1. First render (results is set to []) 2. useEffect (results is set to [JSON]) 3. Second render (RenderIt() call gets first_name)
Yeah! You can render "Loading..." or something in that first render too, whilst the json is being set
Thanks. Closing this request. Appreciate your input.
0

I dont know but i think maybe setFName is the undefined?

const [fName, setFName] = useState("")

1 Comment

Please ignore this statement SetfName(JSON[0].first_name). I am sure its not causing issue.

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.