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?
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.