T
TanStack3y ago
optimistic-gold

First response receives no posts, even though a post is created

I have the following useEffect function, that gets triggered whenever data changes.
const { isSuccess, data } = queryPosts();

useEffect(() => {
if (!isSuccess || !data.data) return;

const validData = postSchema.safeParse(data.data);

if (!validData.success) return;

if (!validData.data.length) {
displayCreatePostModal(true);
return;
}

setPosts(validData.data);
}, [data]);
const { isSuccess, data } = queryPosts();

useEffect(() => {
if (!isSuccess || !data.data) return;

const validData = postSchema.safeParse(data.data);

if (!validData.success) return;

if (!validData.data.length) {
displayCreatePostModal(true);
return;
}

setPosts(validData.data);
}, [data]);
If data does not contain any posts (!validData.data.length), a modal pops up asking the user to create his first post. However, when you create your first post, and you navigate back to the page that contains above code, the modal pops up 1 more time before it hides forever. It seems like after creating the first post, the query data still seems to be empty for a few milliseconds before the posts get loaded into data. Any ideas why this is happening?
1 Reply
optimistic-gold
optimistic-goldOP3y ago
If someone is having the same issue: Besides checking for isSuccess and data, also check for isLoading .

Did you find this page helpful?