Search code examples
javascriptreactjsreact-hooksuse-contextreact-google-login

Unable to get user Data passed as a context value by React useContext


I am using google login for my React application and I want to pass the response from google login i.e. user data to other react components using useContext hook but I'm not getting user data there.

This is my Home.js file where I'm creating context using createContext. Here, I'm storing response from google auth in a state called user and passing that user as the value in UserContext.Provider.

Home.js

import React from "react";
import { GoogleLogin } from "react-google-login";

export const UserContext = React.createContext(null);

const Home = (props) => {
  const baseUrl = process.env.REACT_APP_HEROKU_URL;
  const [user, setUser] = React.useState();

  // Getting response from Google Login
  const responseGoogle = (res) => {
      const googleresponse = {
          UserId: res.googleId,
          Name: res.profileObj.name,
          Email: res.profileObj.email,
          Canvas: "",
      };

      setUser(googleresponse);

    

      const requestOptions = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(googleresponse),
      };

    // Sending User data to backend
    fetch(baseUrl + "User", requestOptions)
      .then((res) => {})
      //.then((data) => console.log(data))
      .catch((err) => console.log(err));

    props.history.push("/board");
  };

  return (
     <UserContext.Provider value={{ user }}>
      <div className="sign-up-mode">
        <div className="panels-container">
          <div className="panel left-container">
            <div className="content">
              <p>
                Login with your gmail id and start using kanban for better
                experience!
              </p>
              <GoogleLogin
                clientId="xxxxxxxxxxxxxxxxxxxxhoubs.apps.googleusercontent.com"
                buttonText="Login with Google"
                onSuccess={responseGoogle}
              />
            </div>
          </div>
        </div>
      </div>
    </UserContext.Provider>
  );
};


export default Home;

This is the component where I'm trying to access UserContext details. Canvas.js

import React, { useState } from "react";
import { UserContext } from "./Home";

const Canvas = () => {
  const user = React.useContext(UserContext);
  console.log("GUSer",user);
}
export default Canvas;

I'm getting null here instead of user Data.


Solution

  • This is most likely due to the async behaviour of fetching data.

    The first time the user will just be empty because it is your initial state

    const [user, setUser] = useState(null)

    //Btw you should always initialize with null or an empty object

    I would recommend using some state to control if the data is loading or not, and return before your main content renders

    something like this

    const [user, setUser] = useState(null)
    const [loading, setLoading] = useState(false)
    
    useEffect(() =>{
      setLoading(true)
      fetch(...)
       .(...)
      .then(data =>{
      setLoading(false)
      setUser(data)
    }
    }, [])
    
    
    if(loading) return <div> loading... please wait </div>
    
    
    return(
      <UserContext.Provider value={{ user }}>
          <div className="sign-up-mode">
    
        ....
    )