I'm fairly new to react, right now I have a function that is fetching some data in my useEffect hook, using a loading state to manage component rendering and then loading my state component with that data, everything is working fine.
But now I have to implement another function to fetch some other data.
How can this be implemented in the best way possible? Do I need to create another useEffect for another fetch function?
Here is my code:
export default function Home() {
const [ageOptions, setAgeOptions] = useState([])
const [age, setAge] = useState('')
const [loading, setLoading] = useState(false)
// get age option from API
useEffect(() => {
setLoading(true)
const fetchAgeOptions = () => {
// transform the data to load properly in my react-select component
function transform(data) {
const options = data.map(function (row) {
return { value: row.id, label: row.description, startAge: row.startAge, endAge: row.endAge }
})
setAgeOptions(options)
setLoading(false)
}
api.get('someurl.com').then(response =>
Object.values(response.data.rows)).then(data => transform(data))
}
fetchAgeOptions()
}, [])
return loading ? <div>Loading...</div> :
<>
<label>Age level</label>
<Select
value={age}
options={ageOptions}
placeholder="All"
onChange={val => {
setAge(val)
}}
/>
</>
}
useEffect-calls, because they might depend on different values. If the second api call depends on a value returned in the first call, use a singleuseEffectand call the second api in the.then()of the first promise (or use async/await).Suspensefor data-fetching, which will solve that problem nicely. But for now, you need to do that yourself.