6

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?

4
  • typeof result not be an array. So it throws error "result.push" is not a function Commented Mar 8, 2017 at 13:32
  • console typeof result Commented Mar 8, 2017 at 13:35
  • It's undefined, How do I setup the first id to be apart of an array so I can push data into it. Commented Mar 8, 2017 at 14:07
  • 1
    use result = JSON.parse(result) || []; Commented Mar 8, 2017 at 14:29

1 Answer 1

13
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));
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.