Search code examples
javascriptreact-nativeparsingsetstateasyncstorage

Read from AsyncStorage, Parse Array, Convert String to Date object


I'm trying to read array from Async storage with "reminders" key.

Problem is JSON.parse cannot convert 'time' key of element in Array to Date object.

I need to read from storage, parse and assign to reminders state using setReminders()

// EXAMPLE DATA IN ASYNC STORAGE
[{day: 'Monday', time: '2020-04-03T15:17:07.554Z', status: false},
{day: 'Friday', time: '2020-04-03T15:17:07.951Z', status: true},]


// LOAD REMINDERS
  useEffect(readReminders, []);

  function readReminders() {
   AsyncStorage.getItem('reminders').then(value =>setReminders(value));
}

Solution

  • You can parse Date from string using Date.parse(string) or new Date(string) like:

    function readReminders() {
       AsyncStorage.getItem('reminders').then(values => {
          const reminders = values.map(item => {
             return {
               ...item,
               time: new Date(item.time)
             }
          });
       });
    }