'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>
)
}
Solution 1:[1]
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>
)
}
Solution 2:[2]
Just get the condition out:
return (
<div>
{item && <Component code={item._id} />}
</div>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Scott |
| Solution 2 | Almo |
