Wednesday 30 June 2021

How to save items with AsyncStorage in one screen and then display it in a different screen

First screen is made to show the history of the saved items from the second screen.

Second screen is a QR CODE Scanner. Once the QR CODE has been scanned it shows a Modal with the information it got from the QR CODE. It also has a Button to save the information. The information that is saved is retrieved in the first screen to a FlatList.

The problem I got is that the information that is saved doesn't show up in the first screen. I only get this in the console.log [Error: [AsyncStorage] Passing null/undefined as value is not supported. If you want to remove value, Use .remove method instead. Passed value: undefined Passed key: @QR

EDIT: I forgot to write that the AsyncStorage Key is exported on the top of the file so it can be imported in the FIRST SCREEN.

CODE: SECOND SCREEN WHERE I SAVE THE INFORMATION.

const [Link, setLink] = useState([]);

const onSuccess = e => {
    setModalVisible(true);
    console.log(e);
    const QRSave = setLink(e);
    storeQRCode(QRSave);
  };

const storeQRCode = QRSave => {
    const stringifiedQR = JSON.stringify(QRSave);

    AsyncStorage.setItem(asyncStorage, stringifiedQR).catch(err => {
      console.log(err);
    });
  };

<Button
   title="Save QR"
   onPress={() => {
   scanner.reactivate();
   storeQRCode();
   showToast();
 }}
/>

CODE: FIRST SCREEN WHERE THE HISTORY IS SHOWN OF THE SAVED INFORMATION.

const [Data, setData] = useState({});

  useEffect(() => {
    restoreQRCode();
  }, []);

  const restoreQRCode = () => {
    AsyncStorage.getItem(asyncStorage)
      .then(stringifiedQR => {
        const parsedQR = JSON.parse(stringifiedQR);
        console.log(stringifiedQR);
        if (!parsedQR || typeof parsedQR !== 'object') return;

        setData(parsedQR);
      })
      .catch(err => {
        console.log(err);
      });
  };

<FlatList
  data={Data}
  keyExtractor={(_, index) => index.toString()}
  renderItem={renderItem}
 />


from How to save items with AsyncStorage in one screen and then display it in a different screen

No comments:

Post a Comment