RepublicOfDavid
RepublicOfDavid

Reputation: 15

Trying to filter by dynamically added property/value in object array and save to state

I was wondering if anybody could help, I have a function that when it runs it will do a fetch and save the object array it gets to a variable, it will then loop through that object array and do another fetch and based on some data in that fetch it will add a new property/value to each object inside the array, I have that working fine, however I then want to filter the array by that new properties value and set the updated object array to state, the problem is the filter doesn't seem to be working, all I get back is the unfiltered data.

Code below, any help would be amazing.

import { useState, useEffect } from 'react'
import ResultsPage from './components/ResultsPage'

const App = () => {

    const [results, setResults] = useState([])
    const searchedRef = useRef()

    useEffect(() => {
       console.log(results)
    }, [results])

    const handleSearch = async () => {
        let searched = searchedRef.current.value
        let res = await fetch(`someAPI/${searched}`)
        let data = await res.json()
        searchResults = data


        res = null
        data = null

        searchResults.map(async (element) => {
            res = await fetch(`someAPI/${element}`)
            data = await res.json()
            element.name = data.name;
        });

        searchResults = searchResults.filter(element => element.name !== null);

        setResults(searchResults)
    }

    return (
        <>
            <input type="text" ref={searchedRef} onKeyDown={handleSearch}/>
            <ResultsPage results={results} />
        </>
    )

}

export default App

Upvotes: 0

Views: 85

Answers (1)

Exifers
Exifers

Reputation: 2822

The map will not wait for each fetch to be done.

Async functions evaluate to Promises, so the mapping will evaluate to an array of Promises.

You need to use Promise.all to wait on an array of Promises.

await Promise.all(searchResults.map(/* ... */))

Example here.

Upvotes: 1

Related Questions