I am new to react and I am building a page component that returns data from an API call and passes the values to my return statement. My page continues to return as blank because the page loads before the variables are returned from the API. I am wondering, how can I wait to render the page until my API has returned a response? The two variables are initialized as so and are not updated until the API response
var userData
const [customer_email, setEmail] = useState();
const [newuserid, setUserId] = useState();
useEffect(() => {
userData = Cookies.get("user-data");
if (userData) {
console.log("Userdata !== null");
try {
userData = JSON.parse(userData);
} catch (e) {
console.log(e);
}
setEmail(userData.email);
setUserId(userData.userID);
}
}, []);
function getCustomer() {
const options = {
method: "GET",
headers: {
Accept: "application/json",
"x-guid": "......",
"x-api-key": ".....",
},
};
if (customer_email != "" && customer_email != undefined) {
try {
console.log("email inside fetch =", customer_email);
fetch(
`https://exampleapi/customers?customer_email=${customer_email}&customer_id=${newuserid}`,
options
)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
}
}
if (customer_email) {
console.log("get customer");
getCustomer();
}
The component return statement:
return (
<>
{customer_email && (
........{irrelevant html here}
)}
);
Note---- This is not a class, it is a function component