Search code examples
reactjsasync-awaitreact-hooksuse-effect

react fetch data from multiple apis with async await and hooks


I am currently fetching data from one endpoint. I want to store another api endpoints data in a state variable in the onload function. However I am not to sure how to fetch multiple end points.

the second end point which I need to call:

'/api/get_all_test_types'

 

This shows the code used to fetch one end point

useEffect(() => {
        async function onLoadCreateUnitTests() {
          
          const results = await get('get_tables_autocomplete/b', user.user)
    
          autoComplete.setTablesAutoComplete(results)
    
        }
    
        onLoadCreateUnitTests()
    
      }, [])

MarkCBall Code:

 useEffect(() => {
    async function onLoadCreateUnitTests() {

      const results = await get('get_tables_autocomplete/b', user.user)
      const resultsAllTestTypes = await get('/api/get_all_test_types')
      autoComplete.setTablesAutoComplete(results)
      setAllTestTypes(resultsAllTestTypes)
  

    }

    onLoadCreateUnitTests()

  }, [])

Error enter image description here


Solution

  • const results = await get('get_tables_autocomplete/b', user.user)
    const resultsAllTestTypes = await get('/api/get_all_test_types')
    autoComplete.setTablesAutoComplete(results)
    setAllTestTypes(resultsAllTestTypes)
    

    Alternatively, you could run these two queries at the same time like so. This will complete as soon as the slower of the two queries completes.

    const getPromises = [
        await get('get_tables_autocomplete/b', user.user),
        await get('/api/get_all_test_types')
    ]
    const getResponses = Promise.all(getPromises)
    autoComplete.setTablesAutoComplete(getResponses[0])
    setAllTestTypes(getResponses[1])
    

    You could get more sophisticated with callbacks to that you start populating your as soon as the first get comes back like so:

    get('get_tables_autocomplete/b', user.user).then(autoComplete.setTablesAutoComplete)
    get('/api/get_all_test_types').then(setAllTestTypes)