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

220
Visualizações
React Native: undefined is not an object (evaluating 'useContext.getItemsCount')

I'm a beginner on React Native and I am getting this error when getItemsCount is called.

*Please Click on the Links to see images

https://i.stack.imgur.com/wbwjZ.png

This is the code for CartIcon.js:

import React, {useContext} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {CartContext} from './CartContext';
export function CartIcon({navigation}){
    const {getItemsCount} = useContext(CartContext);
    return(
        <View style = {styles.container}>
            <Text style = {styles.text}
                onPress = {() => { 
                navigation.navigate('Cart');
                }}
            >Cart ({getItemsCount()}) </Text>
        </View>
        );
}
const styles = StyleSheet.create({
    container: {
        marginHorizontal: 10,
        backgroundColor: '#515b8c',
        height: 40,
        padding: 15,
        borderRadius: 38/2,
        alignItems: 'center',
        justifyContent: 'center',
    },
    text: {
        color: '#ccc',
        fontWeight: 'normal',
    },
});

https://i.stack.imgur.com/ABYHm.png

This is the code for CartContext.js:

import React, {createContext, useState} from 'react';
import {getProduct} from './productService.js';
export const CartContext = createContext();
export function CartProvider(props){
    const [items, setItems] = useState([]);

    function addItemToCart(id){
        const product = getProduct(id);
        setItems((prevItems) => {
            const item = prevItems.find((item) => (item.id == id));
            if(!item){
                return [...prevItems, {
                    id,
                    qty: 1,
                    product,
                    totalPrice: product.price
                }];
            }
            else{
                return prevItems.map((item) => {
                    if(item.id == id){
                        item.qty++;
                        item.totalPrice += product.price;
                    }
                    return item;
                });
            }
        });
    }
    function getItemsCount(){
        return items.reduce((sum,item) => (sum+item.qty),0);
    }
    function getTotalPrice(){
        return items.reduce((sum,item) => (sum+item.totalPrice),0);
    }

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

https://i.stack.imgur.com/HsXoY.png

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

please add this to CartContext.js:

const useCartContext = () => {   
 const context = useContext(CartContext);
 if (context === undefined) { 
  throw new Error('useCartContext must be used within a CartContextProvider');
 }
 return context;
};

and

export { CartProvider, useCartContext };

Go to App.jsx and wrap the whole app with

<CartProvider>
// your app
</CartProvider>

Then in CartIcon.js import useCartContext and replace

const {getItemsCount} = useContext(CartContext);

with

const { getItemsCount } = useCartContext();

Let me know what happens. The idea is to create a hook, which is nicer, but the issue here is that your component needs to be inside a provider for it to have access to the context.

about 4 years ago · Juan Pablo Isaza Relatório

0

Taking a guess, but I would think that your component is outside of the provider, please check that your CartIcon is actually inside of the CartContext.Provider, otherwise it won't have access to it.

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