I am trying to authenticate user using Auth0. Once they have signed in, I would like to obtain the data and store it in my database. If the user exist after authentication, I would like to obtain the relevant product data from my user. But if it does not exist, I would like to axios.post in my database. The problem is now I could not post the data as I do not know what is wrong.
Here is the homepage:
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { Routes, Route } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
export default function Homepage() {
const [userList, setUserList] = useState([]);
const getUser = () => {
// Sending HTTP GET request
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.get(`${process.env.REACT_APP_API_SERVER}/users`, {
headers: {
Authorization: `Bearer eXg`,
},
})
.then((response) => {
const userNames = response.data.map((res) => res.name);
setUserExist(userExist);
});
};
const {
loginWithRedirect,
user,
isAuthenticated,
getAccessTokenSilently,
logout,
} = useAuth0();
useEffect(() => {
// If there is a user, retrieve the user data
if (user) {
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.get(`${process.env.REACT_APP_API_SERVER}/users`, {
headers: {
authorization: `Bearer eXg`,
},
})
.then((response) => {
setUserList(response.data);
});
} else loginWithRedirect();
}, []);
useEffect(() => {
if (isAuthenticated) {
console.log(user);
getUser();
console.log(userList);
//Check to see if curr user exists
if (userList.includes(user.name.trim())) {
console.log("already existed");
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
}); axios.get(`${process.env.REACT_APP_API_SERVER}/products/users/${userId}`, {
headers: {
Authorization: `Bearer eXg`,
},
});
}
//else post user to database
else {
const accessToken = getAccessTokenSilently({
audience: process.env.REACT_APP_AUDIENCE,
scope: process.env.REACT_APP_SCOPE,
});
axios
.post(
`${process.env.REACT_APP_API_SERVER}/users`,
{
firstName: user.nickname,
lastName: user.nickname,
email: user.email,
},
{
headers: {
authorization: `Bearer eXg`,
},
}
)
.then((response) => {
});
}
} else loginWithRedirect();
}, []);
return (
<div>
Hi
</div>
);
}
My backend is showing that it managed to add the user but my database is not showing anything.