I have a form component where users can enter a comment, and a separate component which maps through and displays a list of comments. When a comment is submitted, it only gets displayed once the page loses and then regains focus. How can I have it so that the new comment is displayed when it is submitted without having to lose focus first?
This is the relevant code in my form component
import { useSWRConfig } from 'swr'
const { mutate } = useSWRConfig()
const postData = async (form) => {
setLoading(true);
await axios.post('/api/comments', form);
mutate('/api/comments');
setLoading(false);
}
According to the documentation https://swr.vercel.app/docs/mutation "You can get the mutate function from the useSWRConfig() hook, and broadcast a revalidation message globally to other SWR hooks using the same key by calling mutate(key)*"
This is the component which displays the comments:
const Comments = ({ postId }) => {
const { comments, loading, error } = useComments(postId)
if (error) return <div>An terror has occurred</div>;
if (loading) return <div>Loading comments</div>;
return (
<div className="flex flex-col w-full space-y-2">
{comments && comments[0].map((comment) => (
<Comment
id={comment._id}
key={comment._id}
date={comment.createdAt}
postId={comment._id}
comment={comment.comment}
name={comment.userData[0].name}
photoUrl={comment.userData[0].photoUrl}
/>
))}
</div>
)
}
And this is my useComments hook
export default function useComments (postId) {
const { data, mutate, error } = useSWR(`/api/comments/${postId}`, fetcher);
const loading = !data && !error;
const loggedOut = error && error.status === 403;
return {
loading,
loggedOut,
comments: data,
mutate,
error: error
}
}
Any help very, very much appreciated.