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