Я использую логин google для своего приложения React, и я хочу передать ответ от логина google, то есть данные пользователя, другим компонентам реакции с помощью хука useContext, но я не получаю там данные пользователя.
Это мой файл Home.js, в котором я создаю контекст с помощью createContext. Здесь я сохраняю ответ от google auth в состоянии с именем user и передаю этого пользователя в качестве значения в 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;
Это компонент, в котором я пытаюсь получить доступ к деталям UserContext. 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;
Я получаю здесь null вместо пользовательских данных.