-
Notifications
You must be signed in to change notification settings - Fork 1
/
store.js
49 lines (44 loc) · 1.25 KB
/
store.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
import React, { useState, useEffect, useContext } from 'react'
const GlobalContext = React.createContext()
const useGlobalState = () => {
return useContext(GlobalContext)
}
export { GlobalContext, useGlobalState }
export default function Provider(props) {
const [token, setToken] = useState()
const [loginname , setLoginname] = useState(null)
const [user, setUser] = useState(null)
useEffect(() => {
const accesstoken = localStorage.getItem('accesstoken')
if(accesstoken) {
fetch('https://cnodejs.org/api/v1/accesstoken', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `accesstoken=${accesstoken}`
})
.then((res) => res.json())
.then(res => {
if(res.success) {
setUser({
avatar_url: res.avatar_url,
id: res.id,
loginname: res.loginname
})
setToken(accesstoken)
setLoginname(localStorage.getItem('loginname'))
}
})
}
}, [])
const state = {
token,
user,
setUser,
setToken,
loginname,
setLoginname
}
return <GlobalContext.Provider value={state}>{props.children}</GlobalContext.Provider>
}