/
News.tsx
68 lines (55 loc) · 1.56 KB
/
News.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import * as React from 'react';
import { connect } from 'react-redux';
import * as Redux from 'redux'
import axios from 'axios';
import {v4 as uuidV4} from 'uuid';
import {
INewsItem,
IReducerState,
STORE_NEWS
} from '../store/types';
interface INewsProps extends IStateProps, IDispatchProps {
}
const news:React.FC<INewsProps> = props => {
React.useEffect(() => {
if (!props.news.length) {
axios.get('https://newsapi.org/v2/top-headlines?country=gb&apiKey=5e61e110059c4a9c832c81d75fc8a6ee')
.then(response => {
props.onGetNews(response.data.articles)
})
}
}, [])
let content:JSX.Element| JSX.Element[] = <p>Loading news</p>;
if(props.news.length){
content = props.news.map(article => {
return(
<div key={uuidV4()}>
<h4>{article.title}</h4>
<p>{article.content}</p>
</div>
)
})
}
return (
<div>
{content}
</div>
);
}
interface IStateProps {
news: INewsItem[]
}
const mapStateToProps = (state: IReducerState): IStateProps => {
return {
news: state.news
}
};
interface IDispatchProps {
onGetNews: (newsData:INewsItem[]) => { type: string; payload: INewsItem[]; }
}
const mapDispatchToProps = (dispatch: Redux.Dispatch<any>):IDispatchProps => {
return {
onGetNews: (newsData) => dispatch({type: STORE_NEWS, payload: newsData})
}
};
export default connect(mapStateToProps, mapDispatchToProps)(news);