Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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.

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda