如何将我的登录名(使用 React 创建)与我的 Sanity.io 连接?

问题描述 投票:0回答:1

我一直在尝试通过学习一些 JavaScript 掌握教程来提高我的 React 技能,但碰巧其中一个已经过时了。在教程中,他使用旧的 Google 登录,我可以更新它,问题是他推荐的 Sanity.io 的修复是使用完全不同的应用程序和打字稿进行的(我使用 JavaScript 启动了该项目,并且想完成它)。话虽如此,我如何连接 Google 登录按钮信息(可以工作,但没有获取数据)并将其传输到 Sanity.io?

登录码:

import React from "react"; 
import { useNavigate } from "react-router-dom"; 
import { GoogleOAuthProvider } from "@react-oauth/google"; 
import { GoogleLogin, googleLogout } from "@react-oauth/google"; 
import { FcGoogle } from "react-icons/fc"; 
import covenlogin from "../assets/covenlogin.mp4"; 
import logo from "../assets/logo.png"; 
import { gapi } from "gapi-script"; 
import { useEffect } from "react";
import { client } from "../client";

const Login = () => {
  const navigate = useNavigate();

  const responseGoogle = (response) => {
    localStorage.setItem("user", JSON.stringify(response.profileObj));

    const { name, googleId, imageUrl } = response.profileObj;

    const doc = {
      _id: googleId,
      _type: "user",
      userName: name,
      image: imageUrl,
    };

    client.createIfNotExists(doc).then(() => {
      navigate("/", { replace: true });
    });
  };

  return (
    <div className="flex justify-start items-center flex-col h-screen">
      <div className=" relative w-full h-full">
        <video
          src={covenlogin}
          type="video/mp4"
          loop
          controls={false}
          muted
          autoPlay
          className="w-full h-full object-cover"
        />

        <div className="absolute flex flex-col justify-center items-center top-0 right-0 left-0 bottom-0    bg-blackOverlay">
          <div className="p-5">
            <img src={logo} width="130px" />
          </div>

          <div className="shadow-2xl">
            <GoogleLogin onSuccess={responseGoogle} onError={responseGoogle} />
          </div>
        </div>
      </div>
    </div>
  );
};
export default Login;

用户架构代码:

export default {
    name: 'user',
    title: 'User',
    type: 'document',
    fields: [
        {
            name: 'userName',
            title: 'UserName',
            type: 'string'
        },
        {
            name: 'image',
            title: 'Image',
            type: 'string'
        },
    ] 
}

PS:还需要获取GoogleId,感谢您的阅读。

javascript reactjs react-native sanity
1个回答
1
投票

您必须解码 profileObj 才能解构它。安装 jwt-decode 包,即 npm i jwt-decode。然后将其导入到您正在使用的组件中: import jwt_decode from "jwt-decode";这是 Login.js 的完整代码

import React from 'react'
import { GoogleLogin } from '@react-oauth/google';
import {FcGoogle}  from 'react-icons/fc' 
import sharedVideo from '../assets/share.mp4'
import Logo from '../assets/logowhite.png'
import {client} from '../Client'
import { useNavigate } from 'react-router-dom'
import jwt_decode from "jwt-decode";

const Login = () => {

    const navigate = useNavigate()

    const responseGoogle = (response) => {

    
    try{
        localStorage.setItem('user', JSON.stringify(response.profileObj))
        
        var decodedHeader = jwt_decode(response.credential);
        console.log(decodedHeader)
        //destrcure some of the props from that response
        const {name, sub, imageUrl } = decodedHeader
      
        const doc ={
            _id:sub,
            _type:'user',
            userName: name,
            image: imageUrl, 
        } 
        
        client.createIfNotExists(doc)
        .then(() =>{
            navigate('/', {replace : true} )
        
        })
        .catch(error => console.log(error))
    }
    catch (e) {
        localStorage.clear() //what you need to do incase the jwt is not valid
        console.log(e) //for your own debugging
    }
}
return (
<div className='flex justify-start items-center flex-col h-screen'>
    <div className='relative w-full h-full'>
        <video 
            src={sharedVideo}
            type ='video/mp4'
            muted
            loop
            autoPlay
            className='w-full h-full object-cover'
        />
        <div className='absolute flex flex-col justify-center items-center top-0 bottom-0 right-0 left-0 bg-blackOverlay'>
        <div  className='p-5'>
            <img src ={Logo} alt = 'logo' width='130px'/>
        </div>
        <div className='shadow-2xl '>
              <GoogleLogin
                
                render={(renderProps) =>(
                    <button 
                    onClick={renderProps.onClick} 
                    disabled = {renderProps.disabled}
                    className=' bg-mainColor flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none'>
                        <FcGoogle className='mr-4 '/>Sign In with Google
                    </button>
                )}
                onSuccess = {responseGoogle}
                onFailure = {responseGoogle}
                cookiePolicy = 'single_host_origin'
                />
        </div>
        </div>
    </div>
    </div>
  )
}

export default Login
© www.soinside.com 2019 - 2024. All rights reserved.