Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Carl Wirkus Avatar asked Mar 08 '17 13:03

Carl Wirkus


1 Answers

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));
  }
});
like image 69
vinayr Avatar answered Oct 17 '22 22:10

vinayr