8

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?

0

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.