Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
remove object from array using an id before saving it in local storage in react native

I am saving few data as an object in array in my local storage using AsyncStorage, I am able to do it in following way:

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>

I am passing today's date as an id, because if the date on which I am saving my data, matches an object with same date then it should replace the object from array whose date is also today's data.

for example:

[
  {
    "date": "Jan 02", 
    "description": "1", 
    "id": "Jan 02", 
    "imageURL": "urlImage.jpg", 
    "location": "location", 
    "temperature": "13°C", 
    "weatherType": "Clear"
  }
]

today's date is jan 02, and if I change the description or image and then click save , then this new object should replace the older object whose date is also jan 02

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can achieve this by using Array.filter to filter out based on your Id prop and spread operator to bring it back together.

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;
  };
about 4 years ago · Juan Pablo Isaza Relatório

0

You could do a simple Array#map to update the data.

  setSaveData(prevList => {
    if (prevList.length) {
        return prevList.map(obj => (newItem.date === obj.date) ? newItem : obj);
    }
    return [newItem]
  });

As you've already initialized the value you don't need to set prevList = prevList || []

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda