Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data getting stored using AsyncStorage only after 2-3 submit button clicks in react native

I am calling a function on press of a button, to store my data in local storage using AsyncStorage.

Below is my code to store data using AsyncStorage

const [saveData, setSaveData] = useState([]);

const _submit = async (text, photo) => {
  let newItem;
  
  newItem = {
    description: text,
    imageURL: photo,
  };
  setSaveData(prevList => {
    prevList = prevList || [];
    if (prevList.length < 0) {
      return newItem;
    } else {
      return [...prevList, newItem];
    }
  });
  setLocalItem();
};

const setLocalItem = async () => {
  AsyncStorage.setItem('test2', JSON.stringify(saveData))
    .then(json => console.log('success!'))
    .catch(error => console.log('error!'));
};

const getLocalItem = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('test2');
    const list = JSON.parse(jsonValue);

    console.log('list: ', list);
  } catch (e) {
    console.log('error: ', e);
  }
};

<TouchableOpacity
  onPress={() => {
    _submit (text, photo);
  }}>
  <Text>save</Text>
</TouchableOpacity>

<TouchableOpacity
  onPress={() => {
    getLocalItem();
  }}>
  <Text>get item</Text>
</TouchableOpacity>

My data is getting stored but only after I click save button multiple times. But in console I am getting success even when I click save button only once. But when I click on get item button, I am getting null in console if save is clicked only once.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am not not sure why I have to click save multiple times to store my data.

>Solution :

You’re updating the state incorrectly. And the new state will be available in the next render, so setLocalItem should be called after the state gets updated.

const [saveData, setSaveData] = useState([]);

// this effect updates the storage whenever `saveData` changes
useEffect(() => {
    AsyncStorage.setItem('test2', JSON.stringify(saveData))
    .then(json => console.log('success!'))
    .catch(error => console.log('error!'));
}, [saveData])

const _submit = (text, photo) => {
  const newItem = {
    description: text,
    imageURL: photo,
  };

  // no conditions are required here as the initial state is an array
  setSaveData(prevList => [...prevList, newItem]);
};


const getLocalItem = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('test2');
    const list = JSON.parse(jsonValue);

    console.log('list: ', list);
  } catch (e) {
    console.log('error: ', e);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading