Reputation: 15
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