refactoring and implementing refreshing items list every 2 seconds
This commit is contained in:
@@ -2,7 +2,7 @@ import React from "react";
|
||||
import Select from "react-select";
|
||||
import { connect } from "react-redux";
|
||||
import { CATEGORY_SELECT, ITEMS_CHANGED } from "constants/actionTypes";
|
||||
import { hoc } from "utils/hoc";
|
||||
import { hoc, areObjectEqual } from "utils/helpers";
|
||||
import { createOlxLink } from "utils/createOlxLink";
|
||||
import axios from "axios";
|
||||
|
||||
@@ -29,21 +29,43 @@ const mapDispatchToProps = dispatch => ({
|
||||
onItemsChanged: items => dispatch({ type: ITEMS_CHANGED, items })
|
||||
});
|
||||
|
||||
let lastUpdateTime = null;
|
||||
let interval = null;
|
||||
class App extends React.Component {
|
||||
componentDidMount() {
|
||||
interval = setInterval(() => {
|
||||
if (lastUpdateTime && Date.now() - lastUpdateTime > 2000) {
|
||||
const { category, options, subcategory, onItemsChanged } = this.props;
|
||||
let url = createOlxLink(category, subcategory, options);
|
||||
url = encodeURI(url);
|
||||
if (url) {
|
||||
axios
|
||||
.get(`/api/${url}`)
|
||||
.then(response => onItemsChanged(response.data))
|
||||
.catch(error => console.log(error));
|
||||
}
|
||||
lastUpdateTime = null;
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
clearInterval(interval);
|
||||
}
|
||||
componentWillReceiveProps(newProps) {
|
||||
const { subcategory, category, options } = this.props;
|
||||
if (
|
||||
newProps.subcategory !== subcategory ||
|
||||
newProps.category !== category ||
|
||||
!areObjectEqual(newProps.options, options)
|
||||
) {
|
||||
lastUpdateTime = Date.now();
|
||||
}
|
||||
}
|
||||
handleChange = selectedOption => {
|
||||
this.props.onCategoryChanged(selectedOption);
|
||||
};
|
||||
|
||||
getDataFromOlx = () => {
|
||||
const { category, options, subcategory, onItemsChanged } = this.props;
|
||||
let url = createOlxLink(category, subcategory, options);
|
||||
url = encodeURI(url);
|
||||
axios
|
||||
.get(`/api/${url}`)
|
||||
.then(response => onItemsChanged(response.data))
|
||||
.catch(error => console.log(error));
|
||||
};
|
||||
|
||||
render() {
|
||||
const { category } = this.props;
|
||||
|
||||
@@ -58,7 +80,6 @@ class App extends React.Component {
|
||||
Vozila: <Vozila />,
|
||||
Nekretnine: <Nekretnine />
|
||||
})}
|
||||
<button onClick={this.getDataFromOlx}>Get Data from OLX </button>
|
||||
<ItemsContainer />
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user