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)
}}
/>
</>
}
Use a promise all
useEffect(() => {
setLoading(true)
const fetchMethod1 = () =>{...}
const fetchMethod2 = () =>{...}
const fetchMethod3 = () =>{...}
const fetchMethodN = () =>{...}
Promise.all([fetchMethod1,fetchMethod2,fetchMethod3,fetchMethodN]).then(data=>{
// DATA IS AN ARRAY AND THEY ARE IN ORDER AS PLACED IN
})
}, [])
You might want to create a custom hook called useFetch having inside of it both useEffect and useState, it should return state (initial, loading, error and success) and result, then call the second effect only when the first has the correct state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With