2

I have a React app, which takes 1+n API calls to fetch data into a list which is a state variable (using useState).

The problem I am facing is, the list has duplicate items. Instead of 10 items, it is being populated with 20.

I do empty the list on running it, but I guess setState works asynchronously. How do I fix this?

const [products, setProducts] = useState([]);

    useEffect(() => {
        fetch('http://localhost:1234/')
            .then((response) => response.json())
            .then((data) => {
                setProducts([]);
                for(let i = 0; i < Math.min(10, data['products'].length); i++) {
                    fetch('http://localhost:1234/lookup/'+data['products'][i])
                        .then((response) => response.json())
                        .then((data) => {
                            setProducts(products => [...products, data]);
                        });
                }

            });
    }, []);
Femn Dharamshi
  • 527
  • 1
  • 9
  • 25
  • 1
    Are you using strict mode? https://blog.bitsrc.io/react-v18-0-useeffect-bug-why-do-effects-run-twice-39babecede93 – adsy Nov 05 '22 at 01:01
  • Yes I am. Could not open the blog, since it is paid :( – Femn Dharamshi Nov 05 '22 at 01:05
  • 1
    See https://stackoverflow.com/questions/60305074/react-strictmode-setstate-function-in-useeffect-is-run-multiple-times-when-effe – adsy Nov 05 '22 at 01:13
  • 1
    Do your products have a unique ID? Usually best way to fix this is to allow it to run twice (it is by design in react strict mode in development mode), but make it so the second run is an effectual no-op by merging the products by id. – adsy Nov 05 '22 at 01:14
  • 1
    Let me know if each `product` from `lookup` has a unique `id` key in the object and I will post an answer. – adsy Nov 05 '22 at 01:15
  • 1
    how about checking product state is empty array before fetching? strict mode will call your component lifecycle method more than once https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects – dtm Nov 05 '22 at 03:14
  • Hey! I removed the StrictMode and it worked fine. Yes, the products have unique ids, but for now, removing strict mode worked. Thank you so much for your help!! – Femn Dharamshi Nov 05 '22 at 05:52

0 Answers0