1+ import React , { Component } from "react" ;
2+ import { connect } from "react-redux" ;
3+ import PaginationButton from "./../PaginationButton" ;
4+ import ListItem from "./ListItem" ;
5+ import { fetchStories } from "../../actions" ;
6+ import { withRouter } from "react-router" ;
7+ import TableLoader from "./TableLoader" ;
8+
9+ const parseQueryString = ( str ) => {
10+ if ( ! str ) return { } ;
11+
12+ // remove ? from start of the string
13+ const varStrings = str . slice ( 1 ) ;
14+ const values = varStrings . split ( "&" ) ;
15+ return values . reduce ( ( acc , val ) => {
16+ const a = val . split ( "=" ) ;
17+ acc [ a [ 0 ] ] = a [ 1 ] ;
18+ return acc ;
19+ } , { } ) ;
20+ }
21+
22+ class StoryList extends Component {
23+ constructor ( props ) {
24+ super ( props ) ;
25+ this . state = {
26+ currPage : ( props . data && props . data . page ) || 0
27+ }
28+
29+ }
30+
31+ static getDerivedStateFromProps ( props , state ) {
32+ const { search} = props . location ;
33+ const qParams = parseQueryString ( search ) ;
34+ try {
35+ if ( parseInt ( qParams . page ) != parseInt ( state . currPage ) ) {
36+ props . fetchStories ( qParams . page ) ;
37+ return {
38+ currPage : qParams . page
39+ }
40+ }
41+ } catch ( e ) {
42+
43+ }
44+ return null ;
45+ }
46+ render ( ) {
47+ const { data, loading} = this . props ;
48+ return (
49+ < table >
50+ < thead >
51+ < tr >
52+ < th > Comments</ th >
53+ < th > Vote Count</ th >
54+ < th > UpVote</ th >
55+ < th > News Details</ th >
56+ </ tr >
57+ </ thead >
58+ {
59+ loading ?
60+ < TableLoader rows = { 30 } columns = { 4 } />
61+ :
62+ < React . Fragment >
63+ < tbody >
64+ {
65+ data && data . hits . map ( ( item , i ) => {
66+ return < ListItem data = { item } key = { i } />
67+ } )
68+ }
69+ < tr className = "footer" >
70+ < td colSpan = "4" style = { {
71+ textAlign : 'center' ,
72+ padding : "1.5em 1em"
73+ } } >
74+ < PaginationButton />
75+ </ td >
76+ </ tr >
77+ </ tbody >
78+ </ React . Fragment >
79+ }
80+ </ table >
81+ )
82+ }
83+ }
84+
85+ const mapStateToProps = ( { stories} ) => ( {
86+ data : stories . data ,
87+ loading : stories . loading
88+ } ) ;
89+
90+ export default withRouter ( connect ( mapStateToProps , {
91+ fetchStories
92+ } ) ( StoryList ) ) ;
0 commit comments