React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded?

I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set without completing the request.

The conditional statement is not functioning as expected.


let uploadLoading = false;
let errorMessageUploaded = null;

`function Previews(props) {
   const [files, setFiles] = useState([]);
   const [test, testFile] = useState(null);

   const { getRootProps, getInputProps } = useDropzone({
     noClick: props.uploadDisable,
     accept: "application/vnd.ms-excel, 
     application/vnd.openxmlformats- 
     officedocument.spreadsheetml.sheet",
     onDrop: acceptedFiles => {
     uploadLoading = true;

     var file = acceptedFiles[0];
     fileName = file.path;

     const reader = new FileReader();

     let data = {
       file: null,
       purchase_order_id: props.purchaseorderid
     };

     reader.onload = event => {
      uploadLoading = true;
      data.file = event.target.result.replace(
        "data:application/vnd.openxmlformats- 
        officedocument.spreadsheetml.sheet;base64,",
        ""
      );
    });

     (async () =>
       await axios
         .post(
         baseUrl + "v1/purchaseorder/uploadpurchaseorder",
         data,
         axiosConfig
       )
       .then(response => {
         uploadLoading = false;
         errorMessageUploaded = null;
        window.location.reload();
       })
       .catch(error => {
         errorMessageUploaded = "test";
         uploadLoading = false;
         throw error;
       }))();

     reader.readAsDataURL(file);
     }
  });

  const thumbs = files.map(file => (
    <FontAwesomeIcon icon={faFileExcel} 
    className="excelUploadThumbs" />
  ));

  useEffect(
   () => () => {
 // Make sure to revoke the data uris to avoid memory leaks
  files.forEach(file => URL.revokeObjectURL(file.preview));
  },
  [files]
  );

   return uploadLoading == false ? (
<section className="container">
  <div {...getRootProps({ className: "dropzone" })}>
    <input {...getInputProps()} />
    <p className="dropzoneText1">Drop your file here</p>
    <p className="dropzoneText2">or</p>
    <p className="dropzoneText3">Select file</p>
  </div>
  <aside style={thumbsContainer}>{thumbs}</aside>
</section>
    ) : errorMessageUploaded != null ? (
<section className="container">
  <div className="displayErrorDiv">
    <p className="serviceError"> {errorMessageUploaded} </p>
  </div>
</section>
   ) : (
<section className="container">
  Data is uploading...
  <aside style={thumbsContainer}>{thumbs}</aside>
</section>
);
}`

Answer №1

It seems like the code is a bit unclear, but these tips might be useful.

  1. Consider using uploadLoading and errorMessageUploaded with the useState hook
  2. A cancelToken is needed

let source = Axios.CancelToken.source();

const Send = async (url, method, data) => {
  try {
    source && source.cancel("Operation canceled due to new request.");
    source = Axios.CancelToken.source();
    return await Axios({ method, url, data, cancelToken: source.token });
  } catch (error) {
    if (Axios.isCancel(error)) {
      return Promise.resolve("canceled");
    } else {
      return Promise.reject(error);
    }
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to transfer a JSON object from a frontend Form Input to an Express backend

Apologies for bringing up what may seem like a basic issue, but I've been searching extensively (even through axios' documentation) and haven't been able to pinpoint exactly what I need to resolve this issue. I have created a simple To-Do we ...

Accepting PHP multidimensional array through ajax

My PHP code includes a script to open a database, fetch data, and encode it into JSON format. include_once($preUrl . "openDatabase.php"); $sql = 'SELECT * FROM dish'; $query = mysqli_query($con,$sql); $nRows = mysqli_num_rows($query); if($nRow ...

Storing ng-change event for a checkbox in AngularJS in a valid manner

I have a requirement where I need to handle multiple input checkboxes. The goal is to store the changed checkbox events in an array and then save them when the user submits the changes. <td><input type="checkbox" class="switch" ng-model="each_val ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

Center and justify image inside flexbox using MUI

Can someone explain why my image appears centered but not justified? I'm feeling confused about this. <Box sx={{ display: 'flex', minHeight: '100vh', alignItems: 'center', flexGrow ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Ways to access information from doc.data()

<template> <div> {{ id }} {{ title }} </div> </template> <script> import { useRoute } from 'vue-router' import 'firebase/firebase-firestore' import { db } from '@/fdb' export default ...

Fetching Data Using Cross-Domain Ajax Request

Seeking assistance with a cross-domain Get request via Ajax. The code for my ajax request is as follows: var currency_path = "http://forex.cbm.gov.mm/api/latest"; $.ajax({ url: currency_path, crossDomain:true, type:"GET", dataTyp ...

Solving the Dilemma of Ordering Table Rows by Value in JavaScript

I am currently working on a table and my goal is to display rows in an orderly manner based on the sum of their columns. Essentially, I want the rows with the highest values to be displayed first, followed by rows with second highest values, and so on. Des ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

The countdown feature is failing to update despite using the SetInterval function

My goal is to develop a countdown application using Atlassian Forge that takes a date input and initiates the countdown based on the current date. For instance, if I input "After 3 days from now," I am expecting the result to continuously update every seco ...

Showing the True/False data in Material-UI Table using React

I am currently working on a Material Table event log implementation. This event log is designed to receive data in the form of 'string' and 'boolean' values. While I am able to display the string values without any issue, I am facing di ...

Is there a way to modify a list item in Material UI?

Currently working on a project in React to create a simple todo app. There's an issue with updating the value when an item in the list is clicked. Here's a snippet of my code: export default function ShowTodos () { const [todos, setTodos] = Re ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...

Organized Styled-components

Considering implementing styled-components in my application and questioning the best organizational approach. Usually, styled-components are associated with a particular component for increased reusability. However, what is the recommended method for us ...