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

254
Visualizações
Hooks can only be called inside of the body of a function component. Error: Invalid hook call

I'm trying to implement a shopping cart in my app. I created another file that has the functions I want to be called I keep getting an invalid hook call.

export function CartProvider(props) {
      const [items, setItems] = useState([]);
    
    function addItemToCart() {
        console.log("test")
    }

  return (
    <CartContext.Provider 
      value={{items, setItems, getItemsCount, addItemToCart, getTotalPrice}}>
      {props.children}
    </CartContext.Provider>
  );
}

There is more code in the file but I've narrowed the issue down to this, but as soon as I import the CartContext and make it a const I get the issue.

import {CartContext} from '../CartContext'
const {addItemToCart} = useContext(CartContext)

export default class ProductCard extends Component {


constructor(props) {
    super(props)
    this.state = {
        name: this.props.postname,
        price: this.props.postprice,
        image: this.props.postimage,
        description: this.props.postDescription,
        quantity: this.props.postquantity,
        
    }
    
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use hooks only inside of function components. Therefore you can't use useContext(CartContext) just like that outside of any function component.

I assume that you want to use the context inside of ProductCard? Then you have to either rewrite it to a function component:

function ProductCard (props){
  const {addItemToCart} = useContext(CartContext)


  return ...

}

or wire your class component to the context.

Read more about both ways here

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