Using FileReader on Next.js SSR?

Total
10
Shares

I’ve got a Next.js app, and I am trying to use FileReader to read the contents of an ‘uploaded’ file.

My component looks like below:

  let fileReader;
  let props = {
    multiple: false,
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList($ => [file]);
      fileReader.readAsText(file);
      return false;
    },
    fileList,
  };

  useEffect(() => {
    fileReader = new FileReader();

    fileReader.onload = event => {
      setFileData(JSON.parse(event.target.result));
    };

    setReady(true);
  }, []);

My upload form calls props.beforeUpload to pass the file to it, however the issue I have is that fileReader is undefined at this point.

I’m suspecting this is because of what’s rendered server side and what’s rendered client side, however I’m not sure how to handle this?


Solution

I don’t know what you suspect is correct but if you really think that server side rendering has broken it, then you could use dynamic import of next and use ssr:false to make it render on the client side only, more info

Leave a Reply

Your email address will not be published. Required fields are marked *