-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontextapi.js
53 lines (39 loc) · 1.21 KB
/
contextapi.js
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
import axios from 'axios';
import { createContext, useState, useEffect } from 'react';
import { getNewsAPI, getSourceAPI } from './api';
export const NewsContext = createContext();
const Context = ({children})=>{
const [init, setInit] = useState(0);
const [news, setNews] = useState([]);
const [category, setCategory] = useState("general")
const [index, setIndex] = useState(0);
const [source, setSource] = useState();
const fetchNews = async(reset = category) =>{
const {data} = await axios.get(getNewsAPI(reset));
setNews(data);
if(init!=0){
setIndex(1);
}
}
const fetchNewsFromSources = async() =>{
try{
const {data} = await axios.get(getSourceAPI(source));
setNews(data);
setIndex(1);
}catch(error){
}
}
useEffect(() => {
fetchNews()
setInit(1)
}, [category]);
useEffect(() => {
fetchNewsFromSources()
}, [source]);
return (
<NewsContext.Provider value={{news,index, setIndex, fetchNews, setCategory, category, setSource}}>
{children}
</NewsContext.Provider>
)
}
export default Context;