Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

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",
  },
question from:https://stackoverflow.com/questions/66057983/item-not-displaying-when-pushing-data-from-asyncstorage-to-array-object-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,
  },
});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...