Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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();
    };
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

your mistake is in here

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

setProducts is called at the end of loadProducts, but it is not necessary will update the state before mapData will be called. The solution is to use useEffect as the trigger for next function

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

useEffect(() => { products.length && mapData(), [products.length] }

and so on for the third function renderListProducts

BTW in

products.map((product) =>
                ListProducts.push(
                    <ProductCard product={product} key={product.id} />
                )
            )

you're modifying ListProducts state outside setState, consider do something like

const temp = products.map((product) => <ProductCard product={product} key={product.id} /> )
setListProducts(temp)

instead

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda