Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Outputting results from react-papaparse

I’m working on a Next.js project for the first time and using react-papaparse to read data from CSVs. I’ve got papaparse reading the data correctly and can log it to the console, but when I try to output it on the page itself, I get nothing.

So in the example below, I get output printed in the console, but not on the page itself.

"use client";

import { useState } from "react";
import { usePapaParse } from 'react-papaparse';

const { readRemoteFile } = usePapaParse();
let output = []

readRemoteFile(file, {
  complete: (results) => {
    const data = results.data;
    for (let i = 0; i < data.length; i++) {
      let row = data[i];
      output.push(`<li>${row[2]} – ${row[1]}</li>`);
    }
  }
});

console.log(output);

return (
  <div>
    {output}
  </div>
);

What do I need to do to get output on the page?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In React and Next.js normal Javascript variables that we define doesn’t rerender the page when they change.

In this case you defined output and at first it’s an empty array and then it reads the data and changes the output but it does not make your page rerender so you can’t see the updated output in your page, so that is why we use states inside React applications.

In order to fix it you can use useState hook like this:

const { readRemoteFile } = usePapaParse();
const [output, setOutput] = useState([]);

readRemoteFile(file, {
  complete: (results) => {
    const data = results.data;
    for (let i = 0; i < data.length; i++) {
      let row = data[i];
      setOutput(prev => [`<li>${row[2]} – ${row[1]}</li>`, ...prev]);
    }
  }
});

console.log(output);

return (
  <div>
    {output}
  </div>
);

Using states makes your application rerender whenever the state changes so you can see the updated data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading