Skip to content
Snippets Groups Projects
Sender.js 1.76 KiB
Newer Older
  • Learn to ignore specific revisions
  • import React, { useState, useContext } from "react";
    
    meskio's avatar
    meskio committed
    import { Row, Form, Spinner, Alert } from "react-bootstrap";
    import AuthContext from "./AuthContext";
    
    import { ResponseError } from "./errors";
    
    import { url as cleanUrl } from "./util";
    
    meskio's avatar
    meskio committed
    
    
    function Sender({ url, method, body, onSuccess, onError, children }) {
      const [isLoading, setIsLoading] = useState(false);
      const [error, setError] = useState("");
      const auth = useContext(AuthContext);
    
    meskio's avatar
    meskio committed
    
    
      const submit = (e) => {
    
        if (e) {
          e.preventDefault();
        }
    
    
        setIsLoading(true);
        const fetchMethod = method ? method : "POST";
    
    meskio's avatar
    meskio committed
    
    
        const bodyObj = typeof body === "function" ? body() : body;
        const bodyJson = JSON.stringify(bodyObj);
        fetch(cleanUrl(url), {
          headers: { "x-authentication": auth.token },
          method: fetchMethod,
          body: bodyJson,
    
    meskio's avatar
    meskio committed
        })
          .then((response) => {
    
            setIsLoading(false);
    
    meskio's avatar
    meskio committed
            if (!response.ok) {
              throw new ResponseError(response);
            }
    
            if (response.headers.get("content-type") !== "application/json") {
              return response.text();
            }
            return response.json();
          })
    
          .then(onSuccess)
    
    meskio's avatar
    meskio committed
          .catch((e) => {
            if (
              e instanceof ResponseError &&
    
              onError &&
              onError(e.response.status)
    
    meskio's avatar
    meskio committed
            ) {
              return;
            }
    
    
            setError(e.message);
    
    meskio's avatar
    meskio committed
          });
    
    meskio's avatar
    meskio committed
    
    
      if (isLoading) {
    
    meskio's avatar
    meskio committed
        return (
    
          <Row className="justify-content-center">
            <Spinner animation="border" />
          </Row>
    
    meskio's avatar
    meskio committed
        );
      }
    
      let errorStr;
      if (error) {
        errorStr = (
          <Alert variant="danger">
            Se produjo un error enviando datos: {error}
          </Alert>
        );
      }
    
      return (
        <Form onSubmit={submit}>
          {errorStr}
          {children}
        </Form>
      );
    
    meskio's avatar
    meskio committed
    }
    
    export default Sender;