I have a couple problems with a fetch I'm making to my api in my react profile view. I'm not able to view the data in a p element of the render but I am able to view the user object my profile function spits out in the render... also the function loops forever, never displaying the data in the p element like I want but making unlimited fetchs and spitting out the correct object to the console. I feel like I'm doing a few things wrong here. Help please.
import React, { useState } from "react";
import Loading from "../components/Loading";
import { useAuth0 } from "../react-auth0-spa";
const Profile = () => {
const { loading, user } = useAuth0();
function subSplitter(subscriber){
return subscriber.sub.split("|")[1];
}
var sub = subSplitter(user);
console.log(sub);
const [showResult, setShowResult] = useState(false);
const [apiMessage, setApiMessage] = useState("");
const { getTokenSilently } = useAuth0();
const responseData = [];
const getGames = async () => {
try {
const token = await getTokenSilently();
const response = await fetch("http://localhost:5000/api/users/" + sub, {
headers: {
Authorization: `Bearer ${token}`
}
});
const responseData = await response.json();
setShowResult(true);
setApiMessage(responseData);
console.log(responseData.games);
return responseData.games;
} catch (error) {
console.error(error);
}
};
var stringUser = JSON.stringify(user, null, 2);
var gottenGames = JSON.stringify(responseData.Games, null, 2);
getGames();
if (loading || !user) {
return <Loading />;
};
return (
<div>
<img
src={user.picture}
alt="Profile"
className="rounded-circle img-fluid profile-picture mb-3 mb-md-0"
/>
<h2>{user.name}</h2>
<p className="lead text-muted">{user.email}</p>
<p>{stringUser}</p>
<p>{gottenGames}</p>
</div>
);
};
export default Profile;
getGamesis async, you callgetGames(), but don't wait for it to do anything, I guess somewhere ingetGamesthe value ofloadingis set to false oruseris given a value - but you don't wait for that