Skip to content
Snippets Groups Projects
Commit 8882966d authored by Martin Maroši's avatar Martin Maroši
Browse files

Add method to update user profile.

parent d1e65fff
No related branches found
No related tags found
No related merge requests found
import React, { useState, useEffect, useContext } from "react";
import createAuth0Client from "@auth0/auth0-spa-js";
import PropTypes from "prop-types";
import Api from "./utils/api";
const DEFAULT_REDIRECT_CALLBACK = () => window.history.replaceState({}, document.title, window.location.pathname);
......@@ -48,6 +49,7 @@ export const Auth0Provider = ({ children, onRedirectCallback = DEFAULT_REDIRECT_
setPopupOpen(false);
}
const user = await auth0Client.getUser();
auth0Client.crossOriginVerification();
setUser(user);
setIsAuthenticated(true);
};
......@@ -60,6 +62,25 @@ export const Auth0Provider = ({ children, onRedirectCallback = DEFAULT_REDIRECT_
setIsAuthenticated(true);
setUser(user);
};
const updateProfile = (data) =>
Api.get("/rest/auth").then(([{ _id, ...body }]) =>
fetch("https://dev-8ihcso-1.auth0.com/oauth/token", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body)
})
.then((data) => data.json())
.then(({ access_token }) =>
fetch(`https://dev-8ihcso-1.auth0.com/api/v2/users/${user.sub}`, {
method: "PATCH",
headers: { Authorization: `Bearer ${access_token}`, "Content-Type": "application/json" },
body: JSON.stringify(data)
})
.then((user) => user.json())
.then((user) => setUser(user))
)
);
return (
<Auth0Context.Provider
value={{
......@@ -69,6 +90,7 @@ export const Auth0Provider = ({ children, onRedirectCallback = DEFAULT_REDIRECT_
popupOpen,
loginWithPopup,
handleRedirectCallback,
updateProfile,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
......
......@@ -4,7 +4,9 @@ import Loading from "../components/Loading";
import { useAuth0 } from "../react-auth0-spa";
const Profile = () => {
const { loading, user } = useAuth0();
const { loading, user, updateProfile } = useAuth0();
const handleNameUpdate = () => updateProfile({ user_metadata: { name: "Karlik" } });
if (loading || !user) {
return <Loading />;
......@@ -12,6 +14,7 @@ const Profile = () => {
return (
<div>
<button onClick={handleNameUpdate}>Click</button>
<img src={user.picture} alt="Profile" />
<div>
<h2>{user.name}</h2>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment