Estoy guardando algunos datos como un objeto en una matriz en mi almacenamiento local usando AsyncStorage , puedo hacerlo de la siguiente manera:
const [saveData, setSaveData] = useState([]); useEffect(() => { AsyncStorage.setItem('test4', JSON.stringify(saveData)) .then(json => console.log('success!')) .catch(error => console.log('error!')); }, [saveData]); const _submitWithWeather = async text => { let date = new Date(); const curDate = moment(date).format('MMM DD'); let newItem; newItem = { id: curDate, date: curDate, description: text, imageURL: photo, location: getLocation, temperature: getWeather, weatherType: geType, }; setSaveData(prevList => { prevList = prevList || []; if (prevList.length < 0) { return newItem; } else { return [...prevList, newItem]; } }); }; <TouchableOpacity onPress={() => { _submitWithWeather(text); }}> <Text>save</Text> </TouchableOpacity>Estoy pasando la fecha de hoy como una identificación, porque si la fecha en la que estoy guardando mis datos coincide con un objeto con la misma fecha, entonces debería reemplazar el objeto de la matriz cuya fecha también es la de hoy.
por ejemplo:
[ { "date": "Jan 02", "description": "1", "id": "Jan 02", "imageURL": "urlImage.jpg", "location": "location", "temperature": "13°C", "weatherType": "Clear" } ] la fecha de hoy es el jan 02 de enero, y si cambio la descripción o la imagen y luego hago clic en guardar, entonces este nuevo objeto debería reemplazar el objeto anterior cuya fecha también es el jan 02 de enero
Puede lograr esto usando Array.filter para filtrar según su Id prop y el operador de propagación para volver a unirlo.
const d1 = [ { date: 'Jan 01', description: '1', }, { date: 'Jan 02', description: '2', }, ]; const d2 = { date: 'Jan 01', description: 'abc', }; const getData = () => { const d1WithoutDateToUpdate = d1.filter((d) => d.date != d2.date); const updatedD1 = [...d1WithoutDateToUpdate, d2]; return updatedD1; };Podría hacer un simple Array#map para actualizar los datos.
setSaveData(prevList => { if (prevList.length) { return prevList.map(obj => (newItem.date === obj.date) ? newItem : obj); } return [newItem] }); Como ya ha inicializado el valor, no necesita configurar prevList = prevList || []