Search code examples
reactjscallbacksetstate

React setState is not a function upon adding JSON?


I am attempting to relay data between a file uploader and a table, using a shared ancestor. I have a file uploader but once I add my JSON file I receive the error TypeError: setProductState is not a function.

When I console log my inputJson file it goes though, but when I apply setProductState and input my file I receive this error.

Based on what I've read I don't need a bind because I am using arrow syntax, but I possibly might need a 'this'.

Any thoughts or critiques are welcome.

function FileUploader({ productState, setProductState }) {

  const onDrop = useCallback((acceptedFiles) => {
   // this.setProductState = this.setProductState.bind(this); tried
    acceptedFiles.forEach((file) => {
      const reader = new FileReader()
      reader.onload  = () => {
        const inputJson =
          this.inputJson = inputJson //tried
          JSON.parse(reader.result)
          setProductState(inputJson); //console.log goes through
        }
      reader.readAsText(file)
    })

  }, [])
  const {getRootProps, getInputProps} = useDropzone({onDrop})

  return (
    <div {...getRootProps({style})}>
      <input {...getInputProps()} value={productState}/>
      <p>Drag files here, or click to browse</p>
    </div>
  )
}

Ancestor.js

import React, { useState } from 'react'
import FileUploader from './FileUploader'
import Table from './Table'

const Ancestor = () => {
    const [products, setProducts] = useState({});
    return <>
      <FileUploader productState={products} setProductState={setProducts} />
      <Table productState={products} />
    </>;
  }

export default Ancestor;


Solution

  • I believe you may be confused about how this keyword works. Inside your FileUploader component, this will be a reference to FileUploader, and not to Ancestor.

    You don't need a reference to Ancestor, because you are passing products and setProducts as props. This is the proper way to do it.

    Also, you probably don't mean to do a forEach on acceptedFiles, since it appears that you only desire one file, correct?

    Give this a try.

    function FileUploader(props) {
      // Define an onDrop function to handle drop events
      const onDrop = useCallback((acceptedFiles) => {
        // Get the first file in the list of acceptedFiles
        const file = acceptedFiles[0];
    
        // Create a FileReader
        const reader = new FileReader();
    
        // Create a function to handle the reader onload event
        reader.onload = () => {
          // JSON parse the result from read as text
          let parsed = JSON.parse(reader.result);
          // Call the setProductState function from Ancestor component
          props.setProductState(parsed);
        };
    
        // Read the file, triggering the onload event handler
        reader.readAsText(file);
      }, []);
    
      const { getRootProps, getInputProps } = useDropzone({ onDrop });
    
      return (
        <div {...getRootProps({ style })}>
          <input {...getInputProps()} value={props.productState} />
          <p>Drag files here, or click to browse</p>
        </div>
      );
    }