Supposing that I have a Search component that, when the user types something, would fire an API request to look for what is typed. When using React's useEffect Hook, it would be easy to throttle the API request's with a combination of setTimeout and clearTimeout (which is placed in the clean up function that useEffect returns). However, how can this be done in the Class component version of Search inside the componentDidUpdate lifecycle method?
function Search() {
const [term, setTerm] = React.useState("");
const [results, setResults] = React.useState([]);
React.useEffect(() => {
if(term)
const timeOutId = window.setTimeout(() => {
if (term)
(async () => {
const { data } = await axios.get(
"https://en.wikipedia.org/w/api.php",
{
params: {
action: "query",
list: "search",
origin: "*",
format: "json",
srsearch: term,
},
}
);
setResults(data.query.search);
})();
}, 500);
}
return () => window.clearTimeout(timeoutId);
}, [term]);
return (
/* some JSX */
);
}
class Search extends React.Component {
state = {
term: '',
results: []
}
componentDidUpdate(prevProps, prevState) {
/* ??? */
}
render() {
return (
/* some JSX */
);
}
}
While you could use componentDidUpdate() for this, it would be easier to handle most of the logic in the onChange handler of your input.
There are two important nuances to get right here. The first is that timeoutId should not be in state so it won't trigger any extra renders. The second part is to clean up the timeout after the component unmounts via componentWillUnmount(), so you won't leave any dangling calls to be made after your component no longer exists.
class Foo extends React.PureComponent {
timeoutId = undefined;
state = {
term: ""
};
// Note that this method is bound so we can pass it directly to `onChange`
onTermChange = (event) => {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
const term = event.target.value;
this.setState({ term });
this.timeoutId = setTimeout(() => {
this.timeoutId = undefined;
console.log(`timer fired with "${term}"`);
}, 1000);
};
componentWillUnmount() {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
render() {
return (
<input value={this.state.term} onChange={this.onTermChange} />
);
}
}
ReactDOM.render(<Foo />, document.querySelector("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>