forked from DataStax-Examples/astra-tik-tok
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Home.js
90 lines (79 loc) · 2.69 KB
/
Home.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import React, { useState, useEffect } from 'react'
import FollowersColumn from '../components/FollowersColumn'
import Card from '../components/Card'
import MiniCard from '../components/MiniCard'
import axios from 'axios'
const Home = () => {
const [users, setUsers] = useState(null)
const [userToToggle, setUserToToggle] = useState(null)
let descendingUsers
let topFiveNotFollowing
let topFiveFollowing
//auto populating with dummy data
const addData = async () => {
await axios.post('/.netlify/functions/addData')
}
//fetch all the tik-tok posts to your feed
const fetchData = async () => {
const results = await axios.get('/.netlify/functions/posts')
console.log(results.data)
setUsers(results.data)
}
//toggle user from followed to unfollowed
if (userToToggle) {
const newValue = userToToggle.is_followed ? false : true
const data = {is_followed: newValue}
axios.put('/.netlify/functions/edit', {userId: userToToggle.id, data: data })
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error('error:' + err))
.then(() => fetchData())
setUserToToggle(null)
}
useEffect(() => {
addData()
fetchData()
}, [])
if (users) {
descendingUsers = users.sort((a, b) => a.id < b.id ? 1 : -1)
const following = users.filter(user => user.is_followed === true)
const descendingFollowing = following.sort((a, b) => a.likes < b.likes ? 1 : -1)
topFiveFollowing = descendingFollowing.slice(0, 5)
const notFollowing = users.filter((user) => user.is_followed === false)
const descendingNotFollowing = notFollowing.sort((a, b) => a.likes < b.likes ? 1 : -1)
topFiveNotFollowing = descendingNotFollowing.slice(0, 5)
}
return (
<>
{descendingUsers && (
<div className='container'>
<FollowersColumn users={topFiveFollowing} />
<div className='feed'>
{descendingUsers.map((descendingUser, index) => (
<Card
key={index}
user={descendingUser}
toggleFollow={userToToggle => setUserToToggle(userToToggle)}
/>
))}
</div>
<div className="suggested-box">
<div className="section">
<div className="suggested">
<h2 className="bold">Suggested accounts</h2>
<div className="break" />
{topFiveNotFollowing.map((notFollowingUser, index) => (
<MiniCard
key={index} user={notFollowingUser}
toggleFollow={userToToggle => setUserToToggle(userToToggle)}
/>)
)}
</div>
</div>
</div>
</div>
)}
</>
)
}
export default Home