Search code examples
reactjstypescriptpapaparse

Use fetch data from papaparse


I can't get data from PapaParse. Documentation says function doesn't return anything. I want to save this data in local variable. This code:

papaparse.parse(myData, {
          download: true,
          delimiter: '\t',
          complete: function (results) {
            console.log(results.data);
          }
        });

What i tried do

        let newRes;
        papaparse.parse(myData, {
          download: true,
          delimiter: '\t',
          complete: function (results) {
            console.log(results.data);
            newRes = results.data;
          }
        }); 
console.log(newRes); //undefined

Solution

  • The problem here is that the variable newRes is not assigned yet, when console.log(newRes) is called. The loading and parsing of the file is executed at another time (after) console.log(...) is executed.

    There is no other option than to do everything you want to do with the result in the complete callback.

    To make the code look cleaner you can do the following.

    function handleResult(results) {
      console.log(results.data);
      // ... do your logic here
    }
    
    papaparse.parse(myData, {
          download: true,
          delimiter: '\t',
          complete: handleResult
    });