I have a primitive React program that uses Axios to get data about movies and then print it for the user. The Axios request, and thus printing of information, isn’t supposed to happen until after the user clicks the button at the bottom.
import "./styles.css";
import axios from "axios";
import { useState } from "react";
export default function App() {
const [movie, setMovie] = useState("");
const [title, setTitle] = useState("");
const [runTime, setRunTime] = useState("");
function getMovie(e) {
setMovie(e.target.value);
}
console.log(movie);
function axiosRequest() {
return axios.get(
"https://www.omdbapi.com/?t=" + movie + "&y=&plot=short&apikey=trilogy"
);
}
axiosRequest().then(function (results) {
var response = results.request.response;
var responseObj = JSON.parse(response);
console.log(responseObj);
setTitle(responseObj.Title);
setRunTime(responseObj.Runtime);
});
return (
<div>
<h1 style={{ "text-align": "center" }}>
[INSERT CATCH NAME FOR MOVIE SEARCH ENGINGE HERE]
</h1>
<p>Hello, what movie would you like to know about:</p>
<input type="text" onChange={getMovie} />
<br />
<br />
<button onClick={axiosRequest}>submit</button>
<br />
<br />
Title: {title}
<br />
Runtime: {runTime}
</div>
);
}
I’ve tried writing the event handler as {axiosRequest} and {() => axiosRequest} and {() => axiosRequest()} and even {() => axiosRequest(params)} but nothing works. There’s still the same problem. I even tried attaching .then to the definition of the axiosRequest function, but React didn’t like that. Nor did it like me removing the parentheses and writing it as axiosRequest.then which I thought might stop the function from firing on every render.
So what’s the deal? How do I fix this? I don’t want it to start printing movie data until after the user hits the button.
>Solution :
Move the code that performs fetching and handling the data into a separate function. Currently that code is directly inside the component and will be executed on each render.
function handleClick() {
axiosRequest().then(function (results) {
// ...
setTitle(responseObj.Title);
setRunTime(responseObj.Runtime);
});
}
<button onClick={handleClick}>submit</button>