Item not displaying when pushing data from asyncstorage to array object in React Native?

695 Views Asked by At

I am creating an App in React Native Expo and trying to display data using asyncstorage. The only data which is showing is of static array which I have declared in var temp but when I push the received item in var temp it is not displaying that. I tried using console.log(temp) to check if it is appending data to temp variable. The data is getting appended but is not displaying. Can anyone tell where I am going wrong here

Receiving data from async storage

readData = async () => {
        try {
            const userData = await AsyncStorage.getItem('ticket')
            if (userData != null) {
                temp.push(JSON.parse(userData))
            }
            console.log(temp)
        }
        catch(e) {
            console.log(e)
        }
    }

    useEffect(() => {
        readData()
    }, [])

Displaying data

<View>
                <List.AccordionGroup>
                {
                    temp.map((rowData, index) => (
                        
                            <List.Accordion title={rowData.subject} key={rowData.id} id={rowData.id} style={{marginBottom: 10, backgroundColor: 'white', marginTop: 10,}}>
                                <View style={{padding: 20, backgroundColor: '#FAFAFA'}}>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Project Name:  </Text><List.Item title={rowData.name} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Requested By:  </Text><List.Item title={rowData.request} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Category:  </Text><List.Item title={rowData.category} />
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Priority:  </Text><List.Item title={rowData.priority}/>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Location:  </Text><List.Item title={rowData.location}/>
                                    <Text style={{color: '#7658c1', fontWeight: 'bold', display: 'flex'}}> Description:  </Text><List.Item title={rowData.desc}/>
                                </View>
                            </List.Accordion>
                        
                    ))
                    
                }
            
                </List.AccordionGroup>
                
            </View>

Storing data in AsyncStorage

handleSubmit = async () => {
        let temp = {
            id: Math.floor(Math.random() * 100),
            name: "",
            request: "",
            subject: "",
            category: "",
            priority: "",
            desc: "",
            location: "",
        };
        temp.name = name
        temp.request = request
        temp.subject = subject
        temp.category = category
        temp.priority = priority
        temp.desc = desc
        temp.location = location
        console.log(temp);
        try {
            // await AsyncStorage.setItem("ticket", JSON.stringify(temp))
            await AsyncStorage.setItem('ticket', JSON.stringify(temp))
            console.log(JSON.stringify(temp));
        }
        catch (e) {
            console.log(e)
        }
    }

Static Array

var temp = [{
    id: 1,
    name: "ECM DMS",
    request: "Sohail",
    subject: "Laptop Repair",
    category: "IT",
    priority: "Medium",
    desc: "Urgent Repair",
    location: "Pune",
}];

userData which is stored in asyncstorage

Object {
    "category": "Sharepoint",
    "desc": "Access",
    "id": 20,
    "location": "Mumbai",
    "name": "SharePoint access",
    "priority": "Low",
    "request": "Gurmar",
    "subject": "Access",
  },
2

There are 2 best solutions below

7
On BEST ANSWER

Here is the full example of how you can use AsyncStorage to store and retrieve the data.

Working App: Expo App

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { List } from 'react-native-paper';
const temp = [
  {
    id: 1,
    name: 'ECM DMS',
    request: 'Sohail',
    subject: 'Laptop Repair',
    category: 'IT',
    priority: 'Medium',
    desc: 'Urgent Repair',
    location: 'Pune',
  },
];
export default function App() {
  const [data, setData] = useState([]);

  const handleSubmit = async () => {
    let temp = {
      id: Math.floor(Math.random() * 10000),
      name: 'ECM DMS',
      request: 'Sohail',
      subject: 'Laptop Repair' + Math.floor(Math.random() * 200),
      category: 'IT',
      priority: 'Medium',
      desc: 'Urgent Repair',
      location: 'Pune',
    };

    // console.log(temp);
    try {
      await AsyncStorage.setItem('ticket', JSON.stringify([...data, temp]));
      // console.log(JSON.stringify(temp));
      setData([...data, temp]);
      AsyncStorage?.getItem('ticket').then((userData) =>
        console.log('read data submit:' + JSON.stringify(JSON.parse(userData)))
      );
    } catch (e) {
      console.log('handle:', e);
    }
  };

  const readData = async () => {
    try {
      const userData = await AsyncStorage?.getItem('ticket');
      if (userData != null) {
        setData(JSON.parse(userData));
        console.log('read data:' + JSON.stringify(JSON.parse(userData)));
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    readData();
  }, []);
  return (
    <View style={styles.container}>
      <View>
        {data.length > 0 && (
          <List.AccordionGroup>
            {data?.map((rowData, index) => (
              <List.Accordion
                title={rowData.subject}
                key={rowData.id}
                id={rowData.id}
                style={{
                  marginBottom: 10,
                  backgroundColor: 'white',
                  marginTop: 10,
                }}>
                <View style={{ padding: 20, backgroundColor: '#FAFAFA' }}>
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Project Name:{' '}
                  </Text>
                  <List.Item title={rowData.name} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Requested By:{' '}
                  </Text>
                  <List.Item title={rowData.request} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Category:{' '}
                  </Text>
                  <List.Item title={rowData.category} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Priority:{' '}
                  </Text>
                  <List.Item title={rowData.priority} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Location:{' '}
                  </Text>
                  <List.Item title={rowData.location} />
                  <Text
                    style={{
                      color: '#7658c1',
                      fontWeight: 'bold',
                      display: 'flex',
                    }}>
                    {' '}
                    Description:{' '}
                  </Text>
                  <List.Item title={rowData.desc} />
                </View>
              </List.Accordion>
            ))}
          </List.AccordionGroup>
        )}
      </View>

      <Button title={'ADD MORE DATA'} onPress={handleSubmit} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

0
On

For the UI level changes, you must have to use the state to tell the react-native to update UI when state value changes.

So you have to set temp as a state of your data.

For ex.

const [data, setData] = useState([]);

and when you are about to update the data to show in your design then you have to update the state by calling the setData method and mutate the old state with the new state to update new data with the existing data value.

For ex.

setState(prevState => [...prevState, <<NEW_DATA_OBJECT>>]);

It will update the state and this is the way to show the updated data in UI, you only have to use data const at the place of your temp and update state when your are handling the submission of new data.