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>
);
}
No you cannot because you just don't have an event there... You can do two things:
e.preventDefault with an if (e) e.preventDefault()componentDidMount: // handle form submission
handleSubmit = async (query, e) => {
e.preventDefault();
this.callApi(query)
};
componentDidMount() {
this.callApi("games");
}
callApi(query) {
// code to call api
}