Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6581

React UI Not Displaying Backend API Response

$
0
0

I have a React application that makes a POST request to a backend API to process an image. The backend correctly processes the request and returns the expected response. However, the UI is not displaying the output correctly.

import React, { useState } from "react";import axios from "axios";import { useDropzone } from "react-dropzone";interface ExtractedData {  company: string;  invoice_date: string;  items: { description: string; quantity: number; amount: string }[];  // Changed amount to string for "$745.00" format  total_amount: string;  practitioner: string;  patient: string;  location: string;  currency: string | null;  other_details?: string;}const ImageUploadOCR: React.FC = () => {  const [image, setImage] = useState<File | null>(null);  const [data, setData] = useState<ExtractedData | null>(null);  const [loading, setLoading] = useState<boolean>(false);  const { getRootProps, getInputProps } = useDropzone({    accept: { "image/*": [] },    onDrop: (acceptedFiles) => setImage(acceptedFiles[0]),  });  const handleUpload = async () => {    if (!image) return;    setLoading(true);    const formData = new FormData();    formData.append("image", image);    try {      console.log("Data disk reached");      const response = await axios.post("http://localhost:5000/api/extract", formData, {        headers: { "Content-Type": "multipart/form-data" },      });      // Log the full response to verify the structure      console.log("Response data:", response.data);      // Set data to the state      setData(response.data);      // Optionally log company and invoice_date for debugging      console.log("Company:", response.data?.company);      console.log("Invoice Date:", response.data?.invoice_date);    } catch (error) {      console.error("Error uploading image:", error);    } finally {      setLoading(false);    }  };  return (<div className="p-6 max-w-2xl mx-auto"><div {...getRootProps()} className="border-2 border-dashed p-4 cursor-pointer text-center"><input {...getInputProps()} />        {image ? <p><img src={URL.createObjectURL(image)} /></p> : <p>Drag & drop an image, or click to select</p>}</div><button className="mt-4 bg-blue-500 text-white px-4 py-2 rounded" onClick={handleUpload} disabled={!image || loading}>        {loading ? "Processing..." : "Upload & Extract"}</button>      {data && (<div className="mt-6"><h2 className="text-xl font-bold mb-2">Extracted Data</h2><table className="w-full border-collapse border border-gray-300"><thead><tr><th className="border p-2">Field</th><th className="border p-2">Value</th></tr></thead><tbody><tr><td className="border p-2">Company</td><td className="border p-2">{data?.company || "Not available"}</td> {/* Optional chaining added */}</tr><tr><td className="border p-2">Invoice Date</td><td className="border p-2">{data?.invoice_date || "Not available"}</td> {/* Optional chaining added */}</tr></tbody></table><h3 className="text-lg font-bold mt-4">Items</h3><table className="w-full border-collapse border border-gray-300"><thead><tr><th className="border p-2">Description</th><th className="border p-2">Quantity</th><th className="border p-2">Amount</th></tr></thead><tbody>              {data.items.map((item, index) => (<tr key={index}><td className="border p-2">{item.Description}</td><td className="border p-2">{item.Quantity}</td><td className="border p-2">{item.Amount}</td></tr>              ))}</tbody></table></div>      )}</div>  );};export default ImageUploadOCR;

Issue:The API returns the expected result, but the UI does not display the image.No errors are shown in the console.

Backend response:

{'Currency': None, 'Location': {'Patient Address': '11 Rosewood Drive, Collingwood, NY 33580', "Physician's Address": '102 Trope Street, New York, NY 45568'}, 'Other relevant details': {'Due date': '07/30/23', 'Invoice number': '12245', 'Prescription note': 'A prescription has been written out for patient, for an acute throat infection.', 'Sub total': '$745.00', 'Tax amount': '$157.05', 'Tax rate': '9%'}, 'Patient': 'Kemba Harris', 'Practitioner': 'Dr. Alanah Gomez', 'Total Amount': '$1,902.05', 'company': 'Unknown', 'invoice_date': '07/01/23', 'items': [{'amount': '$745.00', 'description': 'Full Check Up', 'quantity': 1}, {'amount': '$1,000.00', 'description': 'Ear & Throat Examination', 'quantity': 1}]}

image after called successful:

enter image description here

How can I properly display the image output in the UI? What could be causing the issue?


Viewing all articles
Browse latest Browse all 6581

Latest Images

Trending Articles



Latest Images