React-Native - Issue with TypeError: attempting to call a function that is undefined (specifically when using the 'object.map' method)

I've tested everything from the itemList to the reducer and action, it's working fine and successfully deleting the desired item. However, I encountered an error afterwards. I'm not sure where I went wrong. Can someone guide me on what steps I should take next?

// ItemList.js

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { selectAllItems } from '../../../redux/reducer/itemReducer';
import { deleteItem } from '../../../redux/action/ItemAction';
import AppButton from '../../shared/AppButton';

const ItemList = () => {
  const dispatch = useDispatch();

  const itemData = useSelector(selectAllItems);
  function removeHandler(id){
    dispatch(deleteItem(id));
  }

  return (
    <>
      {itemData.map((item) => (
        <View style={styles.itemListContainer} key={item.id}>
          <Text style={styles.textStyle}>{item.id}</Text>
          <Text style={styles.textStyle}>{item.name}</Text>
          <Text style={styles.textStyle}>{item.price}</Text>
          <Text style={styles.textStyle}>{item.availableItem}</Text>
          <View style={styles.operationContainer}>
            <AppButton title="Edit" buttonStyle={buttonStyle.edit} textStyle={buttonStyle.text}/>
            <AppButton title="Remove"  buttonStyle={buttonStyle.remove} textStyle={buttonStyle.text} onPress={() => removeHandler(item.id)}/>
          </View>
        </View>
      ))}
    </>
  )
}

// ItemReducer.js

const itemReducer = (state = initialState, { type, payload } = action) =>{
  switch (type) {
    case ADD_ITEM:
      return { ...state, payload };

    case DELETE_ITEM:
      return { payload };

    default:
      return state;

} }

// itemAction.js

function DELETE_ITEM(filtered){
  return{
    type: 'DELETE_ITEM',
    payload: filtered
  }
}

export function deleteItem(id){
  return function(dispatch, getState){
    const itemData = getState().item;
    const filtered = itemData.filter((item) => item.id !== id);
    dispatch(DELETE_ITEM(filtered));
  }
}

Answer №1

Make sure to double-check your itemData variable to ensure it is not an array. You can handle this by adding the following code snippet:

const data = Array.isArray(itemData) ? itemData : []

...

      {data.map((item) => (
        <View style={styles.itemListContainer} key={item.id}>
          <Text style={styles.textStyle}>{item.id}</Text>
          <Text style={styles.textStyle}>{item.name}</Text>
          <Text style={styles.textStyle}>{item.price}</Text>
          <Text style={styles.textStyle}>{item.availableItem}</Text>
          <View style={styles.operationContainer}>
            <AppButton title="Edit" buttonStyle={buttonStyle.edit} textStyle={buttonStyle.text}/>
            <AppButton title="Remove"  buttonStyle={buttonStyle.remove} textStyle={buttonStyle.text} onPress={() => removeHandler(item.id)}/>
          </View>
        </View>
      ))}

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

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

Using Typescript does not generate any errors when indexing an object with brackets

One interesting thing I've noticed about TypeScript is that it allows me to use bracket notation to access an object via index, even when it only has keys. For example: interface testObject { name: string; id: number; } let first: testObject ...

Inline CSS for altering the appearance of text within a DIV container

Within the confines of this DIV element... <div name="layer1" style="background-color:lightblue;"> <hr>Site:Downtown DataCenter Device: 2KBS</hr> </div> Hello there, I am utilizing Inline CSS Styling. Is it possible to make the t ...

Modify the name of the selected option value

I am working on an html code where I need to replace the values 0, 1, and 2 with USA, Australia, and Canada respectively. I also need to know the name of these values in my MySQL database. Thanks! HTML <form method="post" id="countriesForm" name="cou ...

Ways to set a timeout for a hyperlink?

I have implemented two functions on the same element. One is AJAX for saving an image and the other is prettyPhoto ajax for displaying that image. Here is an example: This is the event > <a rel="prettyPhoto[ajax]" onClick="return false" > onMous ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Utilizing a combination of MVC, jQuery, and Ajax to ensure that JavaScript is fully loaded before proceeding

Utilizing ASP.NET MVC and jQuery, I am loading a PartialView via Ajax which has its own accompanying JavaScript file. Upon successful retrieval of the html content, it is inserted into the DOM. However, there can be a delay between the insertion and the ex ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

Customizing Column Background Color with AngularJS

https://i.sstatic.net/OHFFF.png My current webapp highlights the day of the week on a table for the current day and the day two weeks from now. However, I'm facing an issue with adjusting the highlight if either of these days falls on a holiday. Curr ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Experiencing issues with ng-repeat in AngularJs?

I am currently facing an issue with two tables that are rendering data through AngularJS from two separate C# methods. Both tables have almost identical structures, with the first one being used as a search field and the second one to display names. The pr ...

Refresh information in AngularJS controller

I am currently working on a straightforward AngularJS script that is designed to retrieve data from a socket.io event and then integrate it into the ng template. Below is the JavaScript code I have written for this purpose: // Socket.io logic: var message ...

Create a correct v-model value by utilizing a dot notation string as a reference to the data object

Recently, I created a proxy-component that dynamically renders different components based on the specified :type. Everything was functioning smoothly until I encountered an issue with nested objects within the formData object. An example of this problem i ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

Unraveling JavaScript using regular expressions in Python

I need to parse some JavaScript text using Python. Within the JS code, there is a variable like this: this.products = ko.observableArray([#here is some json, #here is some json]) The observableArray can hold a single JSON object like: observableArray({&a ...

In JavaScript, split each element in an array into individual elements

Is there a way to split elements separated by commas into an array in JavaScript? ["el1,el2", "el3"] => ["el1", "el2", "el3"] I am looking for a solution to achieve this. Can you help me with that? ...