简体   繁体   中英

Using FileReader on Next.js SSR?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM