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?
Advertisement
Answer
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 building your component, which is causing your current error.