refactor: refactor Results component to functional component

This commit is contained in:
2025-07-07 18:05:48 +00:00
committed by Tanner Collin
parent 6f1811c564
commit 366e76e25d

View File

@@ -1,57 +1,36 @@
import React from 'react'; import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import { Helmet } from 'react-helmet'; import { Helmet } from 'react-helmet';
import { sourceLink, infoLine, logos } from './utils.js'; import { sourceLink, infoLine, logos } from './utils.js';
import AbortController from 'abort-controller'; import AbortController from 'abort-controller';
class Results extends React.Component { function Results() {
constructor(props) { const [stories, setStories] = useState(false);
super(props); const [error, setError] = useState(false);
const location = useLocation();
this.state = { useEffect(() => {
stories: false, const controller = new AbortController();
error: false, const signal = controller.signal;
};
this.controller = null; const search = location.search;
}
performSearch = () => {
if (this.controller) {
this.controller.abort();
}
this.controller = new AbortController();
const signal = this.controller.signal;
const search = this.props.location.search;
fetch('/api/search' + search, { method: 'get', signal: signal }) fetch('/api/search' + search, { method: 'get', signal: signal })
.then(res => res.json()) .then(res => res.json())
.then( .then(
(result) => { (result) => {
this.setState({ stories: result.hits }); setStories(result.hits);
}, },
(error) => { (error) => {
if (error.message !== 'The operation was aborted. ') { if (error.message !== 'The operation was aborted. ') {
this.setState({ error: true }); setError(true);
} }
} }
); );
}
componentDidMount() { return () => {
this.performSearch(); controller.abort();
} };
}, [location.search]);
componentDidUpdate(prevProps) {
if (this.props.location.search !== prevProps.location.search) {
this.performSearch();
}
}
render() {
const stories = this.state.stories;
const error = this.state.error;
return ( return (
<div className='container'> <div className='container'>
@@ -89,7 +68,6 @@ class Results extends React.Component {
} }
</div> </div>
); );
}
} }
export default Results; export default Results;