List Returned by Map Function Disappears After One Use

List returned by map function disappears after one use

You are exactly correct. In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. max consumes the whole thing, and min sees the iterator as empty. If you need to use the elements more than once, you need to call list to get a list instead of an iterator.

list object created by map,filter returns empty list

The returned object from filter works like an iterator; you can only iterate over it once:

>>> x=[1,2,3,4,5,6]
>>> odds=filter(lambda n: n%2 == 1, x)
>>> list(odds)
[1, 3, 5]
>>> list(odds)
[]

It's "used up" after the first time you loop over it (which happens in the map() line).

Same is true of the map object.

React component returns list of mapped items, then disappears

This useEffect is not needed. Both useEffects on initial load trying to hit same endpoint with same url params.

 useEffect(() => {
if (categoryId) {
fetch(state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5")
.then((response) => response.json())
.then((data) => {
setPosts(data);
});
}
}, [categoryId]);

And I think arrays are not merged correctly here:

try to replace:
setPosts([...posts, data]);

to:
setPosts([...posts, ...data]);

Why is my react mapped array flashing and then disappearing?

The issue is due to promises inside listFiles function are not handled correctly, so files were returned as empty array, even if this array will be populated in future - react will not detect that and will not rerender the component. Also, it is a bad practice to mix async with .then.catch promises api.

Fixed method:

export const listFiles = async () => {
const listRef = ref(storage, "/");
const listAllResult = await listAll(listRef);

const promises = listAllResult.items.map(async (itemRef) => {
const metadata = await getMetadata(itemRef);
return {
name: metadata.fullPath,
created: metadata.timeCreated
};
});

return Promise.all(promises);
};

Sorry, i cant test it at this moment but if you encounter any issues after that - feel free to comment me and i'll update the answer.



Related Topics



Leave a reply



Submit