Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
How to wait until a value is defined until passing it down as a prop in a component

I have a React component that uses useEffect and axios to receive data from an API. The data is then stored in some state whose initial value is "null". I am trying to pass the state down as a prop but it isn't defined until the useEffect function is complete. I am using double ampersands and it still isn't defined. How do I wait until the state is defined before passing it down as a prop? This is how I am attempting to do it.

import { useState, useEffect } from "react"
import Component from "./Component"
import axios from 'axios'

export default function Items() {
  const [item, setItem] = useState(null)

  useEffect(() => {
    axios.get(`http://testapi/item`).then((res) => {
      setItem(res.data)
    })
  }, [])

  return (
    <div>
      <Component code={item && item._id} />
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Like the others said, I would go for conditional rendering but since the fetch is run on the page load display some loading text and/or a spinner.

import { useState, useEffect } from "react"
import Component from "./Component"
import axios from 'axios'

export default function Items() {
  const [item, setItem] = useState(null)

  useEffect(() => {
    axios.get(`http://testapi/item`).then((res) => {
      setItem(res.data)
    })
  }, [])

  const dataToShow = () => {
    if (item) return <Component code={item && item._id} />
    return <p>...loading</p>
  }

  return (
    <div>
      {dataToShow()}
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza Report

0

Just get the condition out:

return (
    <div>
       {item && <Component code={item._id} />}
    </div>
  )
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!