|
1 |
| -import React from 'react'; |
| 1 | +import React, { useEffect, useState } from 'react'; |
2 | 2 | import Scanner from '../components/Scanner/Scanner';
|
3 | 3 |
|
4 | 4 | const Scan = () => {
|
| 5 | + const [isScanned, setiSScanned] = useState('Scanning...'); |
| 6 | + const [message, setMessage] = useState(''); |
| 7 | + const [serialNumber, setSerialNumber] = useState(''); |
| 8 | + |
| 9 | + const scan = () => { |
| 10 | + if ('NDEFReader' in window) { |
| 11 | + const ndef = new window.NDEFReader(); |
| 12 | + |
| 13 | + ndef.scan().then(() => { |
| 14 | + console.log("Scan started successfully."); |
| 15 | + ndef.onreadingerror = () => { |
| 16 | + console.log("Cannot read data from the NFC tag. Try another one?"); |
| 17 | + }; |
| 18 | + |
| 19 | + ndef.onreading = event => { |
| 20 | + console.log("NDEF message read."); |
| 21 | + onReading(event); |
| 22 | + setiSScanned('Scanned'); |
| 23 | + }; |
| 24 | + }).catch(error => { |
| 25 | + console.log(`Error! Scan failed to start: ${error}.`); |
| 26 | + }); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + const onReading = ({message, serialNumber}) => { |
| 31 | + setSerialNumber(serialNumber); |
| 32 | + for (const record of message.records) { |
| 33 | + console.log("Record type: " + record.recordType); |
| 34 | + console.log("MIME type: " + record.mediaType); |
| 35 | + console.log("Record id: " + record.id); |
| 36 | + switch (record.recordType) { |
| 37 | + case "text": |
| 38 | + const textDecoder = new TextDecoder(record.encoding); |
| 39 | + setMessage(textDecoder.decode(record.data)); |
| 40 | + break; |
| 41 | + case "url": |
| 42 | + // TODO: Read URL record with record data. |
| 43 | + break; |
| 44 | + default: |
| 45 | + // TODO: Handle other records with record data. |
| 46 | + } |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + scan(); |
5 | 51 | return (
|
6 |
| - <Scanner></Scanner> |
| 52 | + <> |
| 53 | + <p>Serial Number: {serialNumber}</p> |
| 54 | + <p>Message: {message}</p> |
| 55 | + <Scanner scanned={isScanned}></Scanner> |
| 56 | + </> |
7 | 57 | );
|
8 | 58 | };
|
9 | 59 |
|
|
0 commit comments