AS10
AS10

Reputation: 271

AsyncStorage not incrementing value on Component load

I am using AsyncStorage and React Native. I have a function that is called in a useEffect and it works, but my AsyncStorage value is not getting updated. It says '1'. I have AsyncStorage as an array, I have also tried that traditional way and the value is not incrementing on load. I have tested on an IOS emulator and an IOS device, but no luck. Below is the function that runs in the useEffect((),[])

 const addFunction = async () => {
        var storage_array = await AsyncStorage.getItem(ASYNC_STORAGE_KEY);

         try {
           if(storage_array) {
             storage_array = JSON.parse(storage_array);
             let flow_complete = 0;
             flow_complete++;
             storage_array.push(flow_complete);
             //storage_array.push(flow_test);
             console.log('THIS IS flow_complete', flow_complete);
             console.log('THIS IS THE ASYNCSTORAGE', storage_array);
           } else {
            flow_complete = 0;
            console.log('Storage array is empty')
           }
         } catch (error) {
           console.log(error);
         }
      }

Upvotes: 0

Views: 69

Answers (1)

Wen W
Wen W

Reputation: 2647

you need to set the item to update the storage.

const addFunction = async () => {
        var storage_array = await AsyncStorage.getItem(ASYNC_STORAGE_KEY);
         try {
           if(storage_array) {
             storage_array = JSON.parse(storage_array);
             let flow_complete = 0;
             flow_complete++;
             storage_array.push(flow_complete);
             //storage_array.push(flow_test);
             console.log('THIS IS flow_complete', flow_complete);
             console.log('THIS IS THE ASYNCSTORAGE', storage_array);
             AsyncStorage.setItem(ASYNC_STORAGE_KEY, JSON.stringify(storage_array));
           } else {
            flow_complete = 0;
            console.log('Storage array is empty')
           }
         } catch (error) {
           console.log(error);
         }
      }

Upvotes: 1

Related Questions