ReactJS
1import React from "react";
2import {tokenContext} from "../shared/context/tokenContext";
3import axios from "axios";
4
5export interface IPostData {
6subreddit: string;
7title: string;
8thumbnail: string;
9author: string;
10score: number;
11created: Date;
12id: string;
13}
14
15export function usePostsData() {
16const [postData, setPostData] = React.useState<IPostData[]>([]);
17const token = React.useContext(tokenContext);
18React.useEffect(() => {
19if(token == 'undefined'){
20return;
21}
22axios.get(
23"https://oauth.reddit.com/best.json?sr_detail=true",
24{headers: {Authorization: `Bearer ${token}`}}
25).then((resp) => {
26let result: Array<IPostData> = [];
27resp.data.data.children.forEach((children: {data: any})=>{
28let newObj: IPostData = {
29author: children.data.author,
30subreddit: children.data.subreddit,
31title: children.data.title,
32thumbnail: children.data.thumbnail,
33score: children.data.score,
34created: new Date(children.data.created*1000),
35id: children.data.id
36};
37
38result.push(newObj)
39})
40setPostData(result);
41})
42.catch(console.error)
43},[token]);
44
45return [postData];
46}
47
48