Problem dealing with asynchronous functions in React

I am writing a code to upload files to the UI. The user presses submit, and that triggers an event (called “onClick” because it isn’t wrapped in a <form>).

There are some type definitions in the code, but that shouldn’t matter at all.

The problem seems the async function “simpleData” inside setState. It seems that this may be the error.

I couldn’t fix it so far.

I have console logged all the steps, and the only problem is that the data won’t render

class Input extends Component {

// main component doing most of the work

  public state: { data: Data[] | "" };

  constructor(props: any) {
    super(props);
    this.state = { data: "" };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.simpleData = this.simpleData.bind(this);
  }

  /**
   * put the relevant parsed information in the state
   */
  public handleSubmit() {
    const input = document.getElementById("files") as HTMLInputElement;
    const files: FileList | null = input.files;
    this.setState(async () => {
      if (files) {
        const d = await this.simpleData(files);
        return { data: d };
      } else {
        return { data: "" };
      }
    });
  }
  /**
   * 
   * parse the files with our code
   */
  public async simpleData(files: FileList) {
    let results: Data[] = [];
    for (let i = 0; i < files.length; i++) { 
      const res: Header = parse(await files[i].arrayBuffer()).meta;
      results.push({ name: files[i].name, meta: res });
    }
    return results;
  }

  render() {
    const data = this.state.data
    console.log(data)
    return (
      <div>
        <input multiple={true} id="files" type="File" />
        <button onClick={this.handleSubmit}>Submit</button>
        <div id="display">{ 
          <Table data={data} /> 
        }</div>
      </div>
    );
  }
}

Problem was I am setting return of setState to an async object. It is quite obvious once you understand it. But someone had to explain it to me.

Now will make handleSubmit async

Aside, but properties are all public anyway, so all that adding public to your Typescript class properties will be doing is likely producing weird JS output once it’s gone through the compiler, it’s completely redundant. And conversely, adding private will not make properties private, you should use the actual syntax for private class properties, ie #, like #myPrivateProperty = "something"

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.