I am trying to fetch data from my database when a /GET is made to the /home page
the issue i face is, when i use the clerk auth’s useUser() hook and call user.emailAddresses[0].emailAddress
inside my useEffect it returns null. if i do it without a useEffect you can see the expected behaviour (but there are constant calls being made to the api
how do i make sure that useUser() does not return null
here’s necessary code snippets
this is within the useEffect() get a null response for user here
export default function Page() {
const [quotes, setQuotes] = useState([]);
const { user } = useUser();
useEffect(() => {
const fetchData = async () => {
try {
if (user) {
const response = await fetch("/api/get-quotes/for-home", {
method: "POST",
body: JSON.stringify({
creator: user.emailAddresses[0].emailAddress,
}),
});
if (!response.ok) {
throw new Error("Failed to fetch quotes");
}
const data = await response.json();
setQuotes(data);
}
} catch (error) {
console.error("Error fetching quotes:", error);
}
};
},[])
return(<>{jsx}</>);
}
this is without a useEffect(), works as expected but keeps making constant calls to the database
export default function Page() {
const [quotes, setQuotes] = useState([]);
const { user } = useUser();
// Function to fetch data
const fetchData = async () => {
try {
if (user) {
const response = await fetch("/api/get-quotes/for-home", {
method: "POST",
body: JSON.stringify({
creator: user.emailAddresses[0].emailAddress,
}),
});
if (!response.ok) {
throw new Error("Failed to fetch quotes");
}
const data = await response.json();
setQuotes(data);
}
} catch (error) {
console.error("Error fetching quotes:", error);
}
};
// Call fetchData immediately when the component is first rendered
fetchData();
return(<>{jsx}</>);
}