1

I am following a tutorial and copied everything but got this error TypeError: event.preventDefault is not a function in the onSubmit() but the event.preventDefault works in the onChange()

Here is the code i have:

import React, { Component } from 'react'
import '../App.css';
import ipfs from './ipfs';

class Add extends Component {
  constructor(props) {
    super(props);

    this.state = {
      ipfsHash: '',
      buffer: null,
    };

    this.captureFile = this.captureFile.bind(this);
    this.onSubmit = this.onSubmit(this);
  }

  captureFile(event) {
    event.preventDefault();
    const file = event.target.files[0];
    const reader = new window.FileReader();
    reader.readAsArrayBuffer(file);
    reader.onloadend = () => {
      this.setState({ buffer: Buffer(reader.result) });
      console.log('buffer', this.state.buffer);
    };
  }

  onSubmit(event) {
    event.preventDefault();
    ipfs.files.add(this.state.buffer, (error, result) => {
      if (error) {
        console.error(error);
        return;
      }
      this.setState({ ipfsHash: result[0].hash });
      console.log('ipfsHash', this.state.ipfsHash);
    });
  }

  render() {
    return (
      <div>
        <h1>Add a Graduate</h1>
        <form onSubmit={this.onSubmit}>
          <input type='file' onChange={this.captureFile} />
          <input type='submit' />
        </form>
        <h1>Transcript of Record</h1>
        <img src={'https://ipfs.io/ipfs${this.state.ipfsHash}'} alt=''></img>
      </div>
    );
  }
}

export default Add;

I don't understand what is the error all about.

Orlyyn
  • 2,296
  • 2
  • 20
  • 32
vccarcido
  • 11
  • 1
  • 3
  • that is the whole code, what i mean is the eventDefault on capture file does not throw a TypeError while the eventDefault in onSubmit does. I want to understand the difference in which the other one throws an error while the other one does not. – vccarcido May 04 '21 at 16:22

1 Answers1

3

In the constructor you are calling onSubmit method instead of binding this: Let's change this.onSubmit = this.onSubmit(this); to:

this.onSubmit = this.onSubmit.bind(this);
Bart Krakowski
  • 1,655
  • 2
  • 8
  • 25
  • Why does this cause a `TypeError: event.preventDefault is not a function`? `this` should cause an error *later* but not with `event` – VLAZ May 04 '21 at 16:34
  • This is because you are passing `this` as an `event`, so `this` does not have a preventDefault method. – Bart Krakowski May 04 '21 at 16:40
  • I'm not passing anything. As far as I'm aware, `this` is not passed as the first argument implicitly, it's still passing the event. The value of `this` *will be `undefined`* because it's lost when the method reference is set as handler [React: “this” is undefined inside a component function](https://stackoverflow.com/q/33973648). So, there would be an error where `this` is used. But `event.preventDefault()` happens earlier. It suggests that `event` is passed as `undefined`. – VLAZ May 04 '21 at 16:47