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

190
Visualizações
TypeError: state.find is not a function

I try to use the find() method but I get

cartItems.find is not a function

what happens? and how to fix it?

import React, {useState} from 'react'

function cart() {
    const [cartItems, setCartItems] = useState([])

    const add = (pro) => {
        const exist = cartItems.find((item) => {
            return item.id === pro.id;
        });
        if (exist) {
            setCartItems(
                cartItems.find((item) => {
                    return item.id === exist.id
                        ? {...exist, qnty: exist.qnty + 1}
                        : item;
                })
            );
        } else {
            setCartItems([...cartItems, {...pro, qnty: 1}]);
        }
    };
    return (
        <div>cart</div>
    )
}

export default cart
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This happen because cartItems is no longer an array.

According to here:

The find() method returns the first element in the provided array that satisfies the provided testing function.

In this part of your code -

setCartItems(
  cartItems.find((item) => {
    return item.id === exist.id
      ? {...exist, qnty: exist.qnty + 1}
      : item;
    })
);

You set cartItems to be the first element of your condition there with find(). So next render, cartItems is no longer an array, but a an item. Which have no find.

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