1- import React , { useEffect , useContext , useReducer } from 'react' ;
1+ import React , { useEffect , useContext , useReducer , useState } from 'react' ;
22import reducer from './reducer' ;
33 // Context created
44let API = "https://hn.algolia.com/api/v1/search?" ;
@@ -9,12 +9,13 @@ const initialState = {
99 nbPages :0 ,
1010 page :0 ,
1111 hits :[ ] ,
12+ popularNews :[ ] ,
1213} ;
1314const AppContext = React . createContext ( ) ;
1415// Now the provider function
1516const AppProvider = ( { children } ) => {
16- const [ state , dispatch ] = useReducer ( reducer , initialState )
17-
17+ const [ state , dispatch ] = useReducer ( reducer , initialState ) ;
18+ const [ showPopularNews , setShowPopularNews ] = useState ( false ) ;
1819
1920
2021 const fetchApiData = async ( url ) => {
@@ -36,6 +37,26 @@ const AppProvider = ({ children }) => {
3637 console . log ( error ) ;
3738 }
3839 } ;
40+ const fetchPopularNews = async ( ) => {
41+ try {
42+ dispatch ( { type :"SET_LOADING" } ) ;
43+ const res = await fetch ( `${ API } query=technology&tags=story` ) ;
44+ const data = await res . json ( ) ;
45+
46+ const sortedNews = data . hits
47+ . filter ( ( item ) => item . num_comments )
48+ . sort ( ( a , b ) => ( b . num_comments || 0 ) - ( a . num_comments || 0 ) ) ;
49+
50+ dispatch ( {
51+ type : "GET_POPULAR_NEWS" ,
52+ payload : sortedNews . slice ( 0 , 7 ) ,
53+ } ) ;
54+
55+ } catch ( error ) {
56+ console . log ( error ) ;
57+ }
58+ } ;
59+
3960
4061 const searchFn = ( searchQuery ) => {
4162 dispatch ( { type :"SEARCH_QUERY" ,
@@ -57,10 +78,13 @@ const AppProvider = ({ children }) => {
5778 fetchApiData ( `${ API } query=${ state . query } &{state.page}` ) ;
5879 } , [ state . query , state . page ] ) ;
5980
81+ useEffect ( ( ) => {
82+ fetchPopularNews ( ) ;
83+ } , [ ] ) ;
6084
6185
6286 return (
63- < AppContext . Provider value = { { ...state , searchFn, getNextPage, getPrevPage} } >
87+ < AppContext . Provider value = { { ...state , searchFn, getNextPage, getPrevPage, showPopularNews , setShowPopularNews } } >
6488 { children }
6589 </ AppContext . Provider >
6690 ) ;
0 commit comments