Carl Wirkus
Carl Wirkus

Reputation: 633

React Native AsyncStorage: Push to an array with a key

Hi I am having trouble with adding values to an array inside AsyncStorage.

AsyncStorage.getItem('savedIds', (err, result) => {
  const id = '1';
  if (result !== null) {
      console.log('Data Found', result);
      result = JSON.parse(result);
      result.push(id);
      AsyncStorage.setItem('savedIds', JSON.stringify(result));
    } else {
      console.log('Data Not Found');
      AsyncStorage.setItem('savedIds', id);
    }
});

AsyncStorage.getItem('savedIds', (err, result) => {
  console.log(result);
});

After my the initial id is set I get the error "result.push" is not a function. What do I need to change to fix this? or is there a more elegant solution to this?

Upvotes: 6

Views: 8900

Answers (1)

vinayr
vinayr

Reputation: 11234

AsyncStorage.getItem('savedIds', (err, result) => {
  const id = [1];
  if (result !== null) {
    console.log('Data Found', result);
    var newIds = JSON.parse(result).concat(id);
    AsyncStorage.setItem('savedIds', JSON.stringify(newIds));
  } else {
    console.log('Data Not Found');
    AsyncStorage.setItem('savedIds', JSON.stringify(id));
  }
});

Upvotes: 13

Related Questions