1
- import React , { useState } from "react" ;
1
+ import React from "react" ;
2
2
import { GoogleLogin , GoogleLogout } from "react-google-login" ;
3
3
import NavLinkStyle from "Styled/NavLink" ;
4
4
import styled from "styled-components" ;
5
- import Cookies from "js-cookie" ;
5
+ import { googleLoginToApi } from "Services/auth" ;
6
+ import { useContext } from "react" ;
7
+ import { authContext } from "Providers/AuthProvider" ;
6
8
7
9
const StyledButton = styled . button `
8
10
${ NavLinkStyle }
9
11
` ;
10
12
11
- const LoginLogoutButton = ( ) => {
12
- const token = Cookies . get ( "token" ) ;
13
+ const LoginLogoutButton = ( { defaultButton = false } ) => {
14
+ const { token, setToken } = useContext ( authContext ) ;
13
15
14
- const [ isLoggedIn , setIsLoggedIn ] = useState ( ! ! token ) ;
15
-
16
- const loginSuccess = response => {
17
- Cookies . set ( "token" , response . tokenId ) ;
18
- console . log ( response )
19
- setIsLoggedIn ( true ) ;
16
+ const loginSuccess = ( response ) => {
17
+ setToken ( response . tokenId ) ;
18
+ googleLoginToApi ( response . tokenId ) . then ( console . log , console . log ) ;
20
19
} ;
21
20
22
- const loginFail = response => {
21
+ const loginFail = ( response ) => {
23
22
alert ( "Login failed" ) ;
24
23
} ;
25
24
26
- const onLogout = response => {
27
- Cookies . remove ( "token" ) ;
28
- setIsLoggedIn ( false ) ;
25
+ const onLogout = ( response ) => {
26
+ setToken ( null ) ;
29
27
} ;
30
28
31
- console . log ( { isLoggedIn } ) ;
32
- return isLoggedIn ? (
29
+ const render = defaultButton
30
+ ? ( text ) => undefined
31
+ : ( text ) => ( { onClick, disabled } ) => (
32
+ < StyledButton onClick = { onClick } disabled = { disabled } >
33
+ { text }
34
+ </ StyledButton >
35
+ ) ;
36
+
37
+ console . log ( { token } ) ;
38
+ return token ? (
33
39
< GoogleLogout
34
40
clientId = { process . env . REACT_APP_GOOGLE_CLIENT_ID }
35
41
buttonText = "Logout"
36
42
onLogoutSuccess = { onLogout }
37
43
onFailure = { onLogout }
38
- render = { ( { onClick, disabled } ) => (
39
- < StyledButton onClick = { onClick } disabled = { disabled } >
40
- Logout
41
- </ StyledButton >
42
- ) }
44
+ render = { render ( "Logout" ) }
43
45
/>
44
46
) : (
45
47
< GoogleLogin
@@ -48,11 +50,8 @@ const LoginLogoutButton = () => {
48
50
onSuccess = { loginSuccess }
49
51
onFailure = { loginFail }
50
52
cookiePolicy = { "single_host_origin" }
51
- render = { ( { onClick, disabled } ) => (
52
- < StyledButton onClick = { onClick } disabled = { disabled } >
53
- Login with Google
54
- </ StyledButton >
55
- ) }
53
+ isSignedIn
54
+ render = { render ( "Login" ) }
56
55
/>
57
56
) ;
58
57
} ;
0 commit comments