export function useComments(urlId: string) {
const [comments, setComments] = useState([] as urlComments[]);
const [error, setError] = useState(null);
const trpcContext = trpc.useContext();
// works
const { data, isLoading, isError } = trpc.comments.getComments.useQuery(
urlId,
{
onSuccess: (data) => {
setComments(data);
},
}
);
// this is where the optimistic update happens
const commentMutation = trpc.comments.createComment.useMutation({
onMutate: async (newComment) => {
const previousComments = [...comments];
const optimisticComment = {
...newComment,
id: `temp-${Date.now()}`,
type: "TEMP",
};
setComments((oldComments) => [optimisticComment, ...previousComments]);
/// above line didnt work, below also no workie
trpcContext.timelines.getTimeline.setData("undefined", (data) => {
return [optimisticComment, ...previousComments];
});
return { previousComments }; // Return the snapshot for potential rollback
},
....
});
const addComment = (commentData) => {
commentMutation.mutate({ urlId, ...commentData });
};
return {
comments,
addComment,
error,
isLoading,
isError,
};
}
export function useComments(urlId: string) {
const [comments, setComments] = useState([] as urlComments[]);
const [error, setError] = useState(null);
const trpcContext = trpc.useContext();
// works
const { data, isLoading, isError } = trpc.comments.getComments.useQuery(
urlId,
{
onSuccess: (data) => {
setComments(data);
},
}
);
// this is where the optimistic update happens
const commentMutation = trpc.comments.createComment.useMutation({
onMutate: async (newComment) => {
const previousComments = [...comments];
const optimisticComment = {
...newComment,
id: `temp-${Date.now()}`,
type: "TEMP",
};
setComments((oldComments) => [optimisticComment, ...previousComments]);
/// above line didnt work, below also no workie
trpcContext.timelines.getTimeline.setData("undefined", (data) => {
return [optimisticComment, ...previousComments];
});
return { previousComments }; // Return the snapshot for potential rollback
},
....
});
const addComment = (commentData) => {
commentMutation.mutate({ urlId, ...commentData });
};
return {
comments,
addComment,
error,
isLoading,
isError,
};
}