Maifee Ul Asad
Maifee Ul Asad

Reputation: 4577

Dictionary error - TypeError: undefined is not an object

I'm trying to store some data as dictionary/JSON in JS in React-Native.

I have defined the dictionary like this :

  const [item, setItem] = useState({});
function onUpdate(id, quantity) {
    console.debug('tab index : ' + tabIndex);
    console.debug('id : ' + id);
    console.debug('quantity : ' + quantity);
    console.debug(item);
    item[tabIndex][id] = quantity;
    console.debug(item);
    //I'm not setting it
    //I have even tried declaring a second object, like :
    //let i=item
    //It also causes the same problem
  }

In log I'm getting :

[Tue Aug 11 2020 13:19:13.195]  DEBUG    tab index : 1
[Tue Aug 11 2020 13:19:13.198]  DEBUG    id : 1
[Tue Aug 11 2020 13:19:13.202]  DEBUG    quantity : 1
[Tue Aug 11 2020 13:19:13.203]  DEBUG    {}
[Tue Aug 11 2020 13:19:13.204]  ERROR    TypeError: undefined is not an object (evaluating 'item[tabIndex][id] = quantity')

Why is that ?

Upvotes: 0

Views: 897

Answers (3)

Muhammad Haris Baig
Muhammad Haris Baig

Reputation: 106

The item object is empty {} this is why you are getting undefined, please check the area where you are setting up the data in items. first check for the undefined condition , if it is undefined create object first and then add.

if(item[tabIndex] === undefined){
    // create object first
} else {
   // directly add the data
}

Upvotes: 0

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

Reason wise , as mentioned by @Amaden , since the item[tabIndex] is undefined , hence when you are trying to add something in that undefined you are getting the error.

So you should first check for the undefined condition , if it is undefined create object first and then add , else you can directly add the data .

var item = {};
var tabIndex = 1;
var id = 1;;

if(item[tabIndex] === undefined){

  item[tabIndex] = {};
  item[tabIndex][id]=10;
} else {

  item[tabIndex][id] = 12;
}

console.log(item);

Upvotes: 1

Amadan
Amadan

Reputation: 198456

If item is {}, then item[tabIndex] is undefined; then item[tabIndex][id] is equivalent to undefined[id], which causes the error.

Upvotes: 3

Related Questions