All files / components/CATME CATMEUploadForm.jsx

100% Statements 23/23
100% Branches 14/14
100% Functions 5/5
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70          218x 218x 218x   218x   31x 31x 31x                   7x       218x 36x 36x 34x 34x 3x 3x   31x 31x     218x 29x 29x 29x     218x                                                
import { useState } from "react";
import { Alert, Button, Form } from "react-bootstrap";
import { useBackendMutation } from "main/utils/useBackend";
 
export default function CATMEUploadForm({ courseId, config, children }) {
  const [file, setFile] = useState(null);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);
 
  const mutation = useBackendMutation(
    (selectedFile) => {
      const data = new FormData();
      data.append("file", selectedFile);
      return {
        method: "POST",
        url: `/api/catme/${config.endpoint}`,
        params: { courseId },
        data,
      };
    },
    {
      onSuccess: setResult,
      onError: (failure) =>
        setError(failure.response?.data?.message ?? config.errorMessage),
    },
  );
 
  const submit = (event) => {
    event.preventDefault();
    if (mutation.isPending) return;
    setResult(null);
    if (!file) {
      setError(config.missingFileMessage);
      return;
    }
    setError(null);
    mutation.mutate(file);
  };
 
  const chooseFile = (event) => {
    setFile(event.target.files[0] ?? null);
    setError(null);
    setResult(null);
  };
 
  return (
    <>
      <Form onSubmit={submit} noValidate aria-label={config.formLabel}>
        <Form.Group
          className="mb-3"
          controlId={`catme-${config.endpoint}-file-${courseId}`}
        >
          <Form.Label>{config.fileLabel}</Form.Label>
          <Form.Control
            type="file"
            accept=".csv,text/csv"
            onChange={chooseFile}
            disabled={mutation.isPending}
          />
        </Form.Group>
        {error && <Alert variant="danger">{error}</Alert>}
        <Button type="submit" disabled={mutation.isPending}>
          {mutation.isPending ? config.pendingLabel : config.buttonLabel}
        </Button>
      </Form>
      {result && children(result)}
    </>
  );
}