1- import React , { useState } from "react" ;
1+ import React from "react" ;
22import { GoogleLogin , GoogleLogout } from "react-google-login" ;
33import NavLinkStyle from "Styled/NavLink" ;
44import 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" ;
68
79const StyledButton = styled . button `
810 ${ NavLinkStyle }
911` ;
1012
11- const LoginLogoutButton = ( ) => {
12- const token = Cookies . get ( "token" ) ;
13+ const LoginLogoutButton = ( { defaultButton = false } ) => {
14+ const { token, setToken } = useContext ( authContext ) ;
1315
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 ) ;
2019 } ;
2120
22- const loginFail = response => {
21+ const loginFail = ( response ) => {
2322 alert ( "Login failed" ) ;
2423 } ;
2524
26- const onLogout = response => {
27- Cookies . remove ( "token" ) ;
28- setIsLoggedIn ( false ) ;
25+ const onLogout = ( response ) => {
26+ setToken ( null ) ;
2927 } ;
3028
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 ? (
3339 < GoogleLogout
3440 clientId = { process . env . REACT_APP_GOOGLE_CLIENT_ID }
3541 buttonText = "Logout"
3642 onLogoutSuccess = { onLogout }
3743 onFailure = { onLogout }
38- render = { ( { onClick, disabled } ) => (
39- < StyledButton onClick = { onClick } disabled = { disabled } >
40- Logout
41- </ StyledButton >
42- ) }
44+ render = { render ( "Logout" ) }
4345 />
4446 ) : (
4547 < GoogleLogin
@@ -48,11 +50,8 @@ const LoginLogoutButton = () => {
4850 onSuccess = { loginSuccess }
4951 onFailure = { loginFail }
5052 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" ) }
5655 />
5756 ) ;
5857} ;
0 commit comments