React Native: The function `useContext.getItemsCount()` is returning a value of undefined, which is not an object

As a newcomer to React Native, I encountered an error when calling getItemsCount.

*To view images, please click on the following links:

https://i.sstatic.net/wbwjZ.png

This snippet shows 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.sstatic.net/ABYHm.png

The code provided below is 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.sstatic.net/HsXoY.png

Answer №1

My suspicion is that your component may be positioned outside of the provider. I recommend verifying that your CartIcon element is nested within the CartContext.Provider in order to ensure proper access.

Answer №2

be sure to integrate the following code snippet into your CartContext.js file:

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

Additionally, include this line for export:

export { CartProvider, useCartContext };

To apply these changes, navigate to App.jsx and encapsulate your entire application with the following tags:

<CartProvider>
// your app
</CartProvider>

After making these adjustments, go to CartIcon.js, import useCartContext, and substitute:

const {getItemsCount} = useContext(CartContext);

with

const { getItemsCount } = useCartContext();

Please inform me of any results or issues encountered. The aim is to streamline the process by creating a hook. However, bear in mind that your component needs to be enclosed within a provider to access the context effectively.

Answer №3

The Error in MySide occurred due to the omission of a return statement when creating the Global context. Please ensure that Side is also checked. ** -> Another possible reason could be not using ContextProvider or wrapping in the App.jsx File App.js File (Often overlooked by many).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficient Checkbox Implementation in ActiveAdmin for Rails 3.1

This query actually encompasses two related inquiries. Enabling "Select all" functionality - In the realm of formtastic, which is used by Active_admin to render forms, how can I implement a button that selects all checkboxes present on the page? While ...

Retrieving a single post from a JSON file using AngularJS

I'm currently delving into AngularJS, but I seem to be stuck on what might be a simple issue. At the moment, I have some hardcoded JSON files with a few persons in them and no actual backend set up yet. In my form, I aim to display a single person ea ...

What is the proper way to select this checkbox using Capybara in Ruby?

Is there a way to successfully check this checkbox?view image description I attempted the following: within('div[id="modalPersistEtapa"]') do element = @driver.find_element(:xpath, '//*[@id="2018_4"]/ ...

How can I use AngularJS resource to fetch data from a URL that requires both query parameters and post data?

Requirement: To send data to an endpoint using a post of data, include the startdate and endate in the querystring of the url. Here's an example: The data payload should only contain the locationIDs and Criteria as shown below. The Resource Definiti ...

Include CLI input into JavaScript variable within the Webpack build process

I am currently attempting to incorporate a variable into my app.js file during the build process. For instance: //app.js var myvar = {{set_from_cli}}; Afterwards, I would like to execute something such as webpack -p --myvar='abc' which would pr ...

Use the Arrow Keys to guide your way through the Page

I am looking to enhance user experience by allowing them to easily navigate through my webpage using the arrow keys on their keyboard. The goal is for users to be able to move from one section to the next in a seamless manner, unless they are focused on an ...

Configuring Laravel to operate on a specific port number?

Currently, I am utilizing nodejs, expressjs, and socket.io to trigger events on my web app via a mobile phone connected to the nodejs server. Although the app is primarily built in JavaScript, I have opted to use laravel for data storage within a database ...

Troubleshooting a Vue 2 component's prop receiving an incorrect value

I'm currently working on creating a menu that navigates between categories. When a category has a sub-category, it should return a boolean value indicating whether it has a sub-category or not. <template> <select><slot></slot ...

The action is not being added to the HTML when the click event is triggered

I'm developing a GIF generator, with the aim of generating clickable buttons that will dynamically add 10 gifs based on the search term to the page. Although the click event is triggering the console log, it's not adding divs with gif images and ...

Utilizing accurate server URLs (Codeigniter) for local JavaScript execution

Help Needed: Issue with Correct Path Names in Local JavaScript with CodeIgniter Backend I am facing difficulties in using the correct path names in local JavaScript while working with a backend in CodeIgniter. -user_data -application -system -assets In ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Encountered error: "Node.js and socket.io: Address already in use"

Experimenting with chat using Node.js and socket.io Currently, I am running Ubuntu 12.04 as a user and have a folder "pp" on my desktop. In this folder, I have placed a server file named server.js. Below is the client code: $(document).ready(function() ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...

Utilize AJAX/JS and Django to seamlessly upload files

This is the form for my popup window. <div class="popup media-upload-form"> <div class="border cf"> <div class="close">X</div> </div> <form class="cf" action="" method="POST" enctype="multipart/form-data"> ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

Angular 4 application encountering 'Access-Control-Allow-Origin' issue

Attempting to reach the following URL: Manually accessing works without issue. However, trying to access via an Angular 4 request results in: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://loca ...

"Enhance User Interaction with a Bootstrap Popup when Submitting Form Data via

As a junior web master, I have a simple question to ask. I have created a single page application for a client with a contact form at the end of the page. The validation is done using Bootstrap, but the only method I know to send the form data to a mail id ...

Switching from a click event to a hover event in JavaScript

I've been experimenting with animating a burger bar on hover and came across an example online that I managed to adapt for mouseenter functionality. However, I'm struggling to make it revert back to the burger bar shape once the mouse leaves on m ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...