Search code examples
reactjsgraphqlapollo

social login - how to use variables outside of function in react?


I try to use social login.

if I success to login in kakao. they give me access_token and I use it to mutation to my server

below is my code

import { useMutation } from "react-apollo-hooks";
import { KAKAO_LOGIN } from "./AuthQuery";


export default () => {
  const kakaoLoginMutation = useMutation(KAKAO_LOGIN, {
    variables: { provder: "kakao", accessToken: authObj.access_token },
  });

  const kakaoLogin = (e) => {
    e.preventDefault();
    window.Kakao.Auth.login({
      success: function (authObj) {
        console.log(authObj.access_token);
      },
    });
  };
  if (authObj.access_token !== "") {
    kakaoLoginMutation();
  }
  return (
    <a href="#" onClick={kakaoLogin}>
      <h1>카카오로그인</h1>
    </a>
  );
};

if I success to login using by function kakaoLogin, it give authObj. console.log(authObj.access_token) show me access_token

and I want to use it to useMutation. but it show to me authObj is not defined.


Solution

  • Looks like you're looking for a local state to hold authObj

    const [authObj, setAuthObj] = useState({});
    
    const kakaoLogin = (e) => {
      e.preventDefault();
      window.Kakao.Auth.login({
        success: function(authObj) {
          setAuthObj(authObj);
        },
      });
    };
    
    const kakaoLoginMutation = useMutation(KAKAO_LOGIN, {
      variables: {
        provder: "kakao",
        accessToken: authObj.access_token
      },
    });
    
    if (authObj.access_token !== "") {
      kakaoLoginMutation();
    }