Bagus Amrullah Fikri
Bagus Amrullah Fikri

Reputation: 395

Saving Array of Object on AsyncStorage React Native

I am trying to both save & read the data which is array of object inside my local storage. The saving process is already done , below is my object structure to give more insight :

enter image description here

There are two type of category : INCOME and OUTCOME, hence i am using those category for my KEY on saving the entry, the full code is shown below :

const onSubmit = async () => {
    const newData = {
      category: type,
      title: title,
      note: note,
      amount: amount,
      date: date,
    };
    try {
      const jsonData = JSON.stringify(newData);
      let existingTransactions = await getTransaction(newData.category);
      const updatedTransactions = [...existingTransactions, jsonData];
      await AsyncStorage.setItem(
        newData.category,
        JSON.stringify(updatedTransactions)
      );
    } catch (err) {
      console.log(err);
    }
  };

  const getTransaction = async (category) => {
    let transactions = await AsyncStorage.getItem(category);
    if (transactions) {
      return JSON.parse(transactions);
    } else {
      return [];
    }
  };

Basically before saving new object , I need to read the previous saved array and then push the new object into the existing array, and finally save them all using the setItem. Below is the array of object whenever i saved new object it printed on the console :

enter image description here

My question are :

1. Am I doing the right thing with the KEY ? Or i should make the key unique for each object ?

2. Whenever I tried to read those array using getItem and then map the array, I cant get the data that I wanted , I can only get the full object like below :

enter image description here

But I cant get let say only the category or only the title of each object.

Here are the codes that i use to read the array :

const [data, setData] = useState([]);
  useEffect(() => {
    async function fetchData() {
      const value = await AsyncStorage.getItem(category);
      const arrayData = JSON.parse(value);
      console.log(arrayData);
      setData(arrayData);
    }
    fetchData();
  }, []);
  
 {data.map((entry, index) => {
   return <Text key={index}>{entry}</Text>;
 })}

Upvotes: 3

Views: 5405

Answers (2)

yogski
yogski

Reputation: 301

I'm familiar with React.js, not React Native. However, from what I've read, you've made a mistake using JSON.stringify too early.

// const onSubmit = async () => {
// ...
    try {
      const jsonData = JSON.stringify(newData); // convert object to string
      let existingTransactions = await getTransaction(newData.category);
      const updatedTransactions = [...existingTransactions, jsonData]; // you're having array of string, not array of object
      await AsyncStorage.setItem(
        newData.category,
        JSON.stringify(updatedTransactions)
      );
    } 
// ...

Get rid of first JSON.stringify, then change the code little bit like this

// const onSubmit = async () => {
// ...
    try {
      let existingTransactions = await getTransaction(newData.category);
      const updatedTransactions = [...existingTransactions, newData]; // notice the newData here
      await AsyncStorage.setItem(
        newData.category,
        JSON.stringify(updatedTransactions)
      );
    } 
// ...

Clear the storage first, then you can try again. Demikianlah.

Upvotes: 2

Ruchi Tiwari
Ruchi Tiwari

Reputation: 261

Anything stored in AsyncStorage should have a unique key to fetch it accordingly

You can store the array and fetch the array as done accordingly and then to get the specific json object by category name

  let category = transactions.find(o => o.category === 'Your category name');

Upvotes: 1

Related Questions