I am trying out the new functions of Next.js 13 with the /app folder, but in a simple client-side component that handles an input form, I am trying to use FileReader but receive an error when browsing.
This is the summary of the code:
"use client";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import useStore from "../app/store";
export default function FileUploader() {
const [files, setFiles] = useState([]);
const router = useRouter();
const addFile = useStore((state) => state.addFile);
const fileReader = new FileReader();
const onFileSelect = (event) => {
event.preventDefault();
setFiles(event.target.files);
console.log(event.target.files);
};
useEffect(() => {
if (files[0] == null) return;
let FileToString = fileReader.readAsText(files[0]); // get error at this line
addFile(FileToString);
router.push("/file/" + filename);
}, [files]);
return (
<input
id="dropzone-file"
type="file"
className="fileInput"
onChange={onFileSelect}
/>
);
}
Error:
wait - compiling...
event - compiled client and server successfully in 3.4s (758 modules)
ReferenceError: FileReader is not defined
at FileUploader (webpack-internal:///(sc_client)/./components/FileUploader.js:27:24)
...
What am I doing wrong?
Like accessing window, any browser-specific code in Next.js needs to run on the client. If you want to use FileReader, which is part of the browser API, add it to your useEffect, like so:
useEffect(() => {
const fileReader = new FileReader();
// ...
}, [files]);
This way, Next.js won't look for the definition of a FileReader while rendering your component on the server. Yes, even client components render first on the server, and get hydrated on the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With