Papa parse is giving type error Object possibly null for File type input

Viewed 661

I have a simple react component where I am using a HTML input (type='file') to upload files. I am using Papa Parse to parse the csv file to JSON. I am doing it with typescript. I have installed both @types/node and @types/papaparse. I would be really great if someone can solve this. I am new to TS.

Please see the below code and attached snapshot of error message I am gettingenter image description here

  export const UploadFile: React.FC<{}> = () => {
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [highlight, setHighlight] = useState<boolean>(false)

  const openFileDialog = () => {
    if (fileInputRef.current !== null) {
      fileInputRef.current.click()
    }
  }

  const onFilesAdded = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (files) {
      const array = fileListToArray(files)
    }
  }

  const fileListToArray = (list: FileList) => {
    const fileList = []
    for (let i = 0; i < list.length; i++) {
      fileList.push(list.item(i))
      if (list !== null && list.item !== null) {
        const file = list.item(i)
        parse(file, {
          complete: (results: object) => {
            console.log(results)
          }
        })
      }
    }
    return fileList
  }
1 Answers

You should guard the call with if(file !== null) like so:

export const UploadFile: React.FC<{}> = () => {
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [highlight, setHighlight] = useState<boolean>(false)

  const openFileDialog = () => {
    if (fileInputRef.current !== null) {
      fileInputRef.current.click()
    }
  }

  const onFilesAdded = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (files) {
      const array = fileListToArray(files)
    }
  }

  const fileListToArray = (list: FileList) => {
    const fileList = []
    for (let i = 0; i < list.length; i++) {
      fileList.push(list.item(i))
      if (list !== null && list.item !== null) {
        const file = list.item(i)
        if(file !== null) {
          parse(file, {
            complete: (results: object) => {
              console.log(results)
            }
          }
        })
      }
    }
    return fileList
  }

This is needed since File Input are sometimes null for one reason or other.

Related