Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Is there any way to use event object inside React's componentDidMount method?

I have two components, the App component and a SearchBar Component. The SearchBar component is a functional component and the form submission is handled by a method called handleSubmit which is defined in App component and is passed down through props. The handleSubmit method which is defined in the App component which first prevents the default behavior of browser form submission and then makes an asynchronous call to a YouTube API. The API call is always successful and works whenever I search for something through the form, say "bulidings". But I want to show some default video when the component is first rendered, e.g. "games". So I called the handleSubmit method in componentDidMount, which gives an error "Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'preventDefault')". Is there any way I can use event object inside componentDidMount?

Here is my code:

App:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
      videos: [],
      selectedVideo: null,
    };  }


  componentDidMount() {
    this.handleSubmit("games");
  }

  // handle form submission
  handleSubmit = async (query, e) => {
    e.preventDefault();

   // API call
  };

    // handle change in input
  onIputChange = (e) => {
    const inputValue = e.target.value;
    this.setState({ inputValue });
  };

    render() {
    const inputValue = this.state.inputValue;
    return (
        <div>
          <SearhBar
            handleSubmit={(e) => this.handleSubmit(inputValue, e)}
            inputValue={inputValue}
            onInputChange={this.onIputChange}
          />
        </div>
    );
  }

SearchBar:

function SearhBar(props) {
  return (
    <form onSubmit={props.handleSubmit}>
      <label>Search Video</label>
      <input
        onChange={props.onInputChange}
        type="text"
        value={props.inputValue}
      />
    </form>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

No you cannot because you just don't have an event there... You can do two things:

  • surround e.preventDefault with an if (e) e.preventDefault()
  • extract the common callApi part to a method and call that method from componentDidMount:
  // handle form submission
  handleSubmit = async (query, e) => {
    e.preventDefault();

    this.callApi(query)
  };
  componentDidMount() {
    this.callApi("games");
  }

  callApi(query) {
    // code to call api
  }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda