'React State updates too late

I try to render a list with products but unfortunely the list updates too late. The Products List is empty. When I execute it the second time it works. Is there any solution?

Thank you very much!

export const Products = (props) => {
    const [products, setProducts] = useState([]);
    const [ListProducts, setListProducts] = useState([]);
    const [List, setList] = useState([]);

    const loadProducts = async (categorieid) => {
        const apiProducts = await axios.get(`${url}/products/${categorieid}`);
        setProducts(apiProducts.data.body);
    };

    const mapData = async () => {
        if (products && products.length) {
            products.map((product) =>
                ListProducts.push(
                    <ProductCard product={product} key={product.id} />
                )
            );
            setListProducts(ListProducts);
        } else {
            List.push(
                <div className="column">
                    <span className="title has-text-grey-light">
                        No products found!
                    </span>
                </div>
            );
        }
    const renderListProducts = () => {
        return <div className="container">{ListProducts}</div>;
    };

    const writeCategory = async (kategorieId) => {
        await loadProducts(kategorieId);
        await mapData();
        await renderListProducts();
    };
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source