Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - how to fetch multiple data with useEffect

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)
        }}
      />
    </>
}
like image 351
fjurr Avatar asked Jan 29 '20 14:01

fjurr


Video Answer


2 Answers

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 
})
    
  }, [])

like image 153
Ernesto Avatar answered Oct 22 '22 21:10

Ernesto


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.

like image 36
yairniz Avatar answered Oct 22 '22 21:10

yairniz