最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Outputting results from react-papaparse - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Nov 22, 2024 at 20:52 Ali Navidi 1,0352 gold badges8 silver badges26 bronze badges asked Nov 20, 2024 at 7:42 TyssenTyssen 1,71119 silver badges40 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论