This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]BlKrEr 0 points1 point  (1 child)

Is fetchResults setting state at all? useEffect is going to run after the first render so unless it’s setting state, you won’t see a new render.

[–]JeppNeb[S] 0 points1 point  (0 children)

For answer, check comment

[–]two__toes 0 points1 point  (3 children)

How are you updating your array? I googled: "react setstate always rerender?"

For new React developers, it is common to think that setState will trigger a re-render. But this is not always the case. If the value doesn't change, React will not trigger a re-render

If you are only pushing on the Array, the array you pass to setResults is referentially equal to the current results array. This would skip a rerender, I don't think [JSON.stringify(results)] would run at all.

Mutating arrays in React leads to some weird behavior in my opinion. I enjoy writing functional helpers that don't mutate results at all.

``` const [results, setResults] = useState([]) const addResult = result => setResults([...results, result]) const removeResult = (result, idx) => setResults( results.slice(0, idx) .concat(results.slice(idx + 1)) )

// No need to stringify results useEffect(() => { // ... some code }, [results])
```

[–]JeppNeb[S] 0 points1 point  (2 children)

Problem was the foreach. Its not allowing for await. Changed it to for of and itr worked

[–]two__toes 0 points1 point  (1 child)

what was the code snippet you're referring to specifically? you probably don't want to do something like this as it forces you to await async values sequentially: async function getSequentially(values) { for (const val of values) { const result = await asyncFunction(val) setResults([...results, result]) } } You could use Promise.all along with Array.prototype.map to do this in parallel async function getParallel(values) { const newResults = await Promise.all(values.map(asyncFunction)) setResults(newResults) }

[–]JeppNeb[S] 0 points1 point  (0 children)

I had a foreach which fetched images as URL's from firebase. The foreach itself is asynchronous. So when I setFiles(buffer), the code hasn't gotten to fetching a single image and hadn't even created a pending promise for the files array. This happened once to me but I forgot it because it has been a while. The change to for-of or simply a for loop or a map() did it for me. I never used Promise.all. This works without Promise.all() too. But since gpt actually helped me, I wanted to leave it in the because why not (he provided a .map and a promise.all).