API - connecting API in react component

0 votes
60 views
added Feb 14 in API by lcjr First Warrant Officer (11,850 points)
import fetch from 'isomorphic-unfetch';  

const CSVUploader = ({ onUpload }) => {
  const [selectedFile, setSelectedFile] = useState(null);
  const router = useRouter();

  const handleFileChange = e => {
    const file = e.target.files[0];
    setSelectedFile(file);
  };

  const handleUpload = async () => {
    if (selectedFile) {
      try {
        const formData = new FormData();
        formData.append('csvFile', selectedFile);
        
        const CSV_API_ENDPOINT = 'YOUR_API_ENDPOINT';
        const response = await fetch(CSV_API_ENDPOINT, {
          method: 'POST',
          body: formData
        });
        
        if (!response.ok) {
          throw new Error('Failed to upload file');
        }

        const csvData = await response.text();
        onUpload(csvData);

        // Redirect to TQ page once uploaded
        router.push('/ERP-thank-you');
      } catch (error) {
        console.error('Error uploading file:', error);
        // Handle error, show error message, etc.
      }
    }
  };

  return (
    <div>
      <label
        className="file-input-label">
        <span>Browse the files</span>
        <input
          type="file"
          accept=".csv"
          onChange={handleFileChange}
        />
      </label>
      <p className="upload-info">
        Maximum upload file size: 100MB
      </p>
      <button onClick={handleUpload}
      >
        Upload CSV
      </button>
    </div>
  );
};

export default CSVUploader;

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...