I have a server action that fetches comments from an API:
"use server"
let url = `https://api.xxxxxx/comments.php`
export default async function getComments() {
try {
const resp = await fetch(url, {
next: { tags: ['comments'] }
})
const {data} = await resp.json()
return data
} catch(err) {
return {
error: err.message
}
}
}
I also have a Form.js
component which is a client component marked with the 'use client'
directive. I use the form to create new comments by sending the form data to another server action createComment
.
Form.js
'use client'
import createComment from "@/actions/createComment"
import { useRef } from "react"
export default function CreatCommentForm({addOptimisticComment}) {
const formRef = useRef()
const submitForm = async (formData) => {
addOptimisticComment({
"id": Math.random(),
"title": formData.get('f_k_page_title'),
"body": formData.get('f_body')
})
await createComment(formData)
formRef.current.reset();
}
return (
<div>
<form action={submitForm} ref={formRef}>
<input type="text" name="f_k_page_title" placeholder="Title" className="border" /> <br/>
<textarea name="f_body" placeholder="Body" className="border"></textarea> <br/>
<button type="submit" className="p-2 mt-3 border bg-neutral-300">CreatCommentForm</button>
</form>
</div>
)
}
createComment.js
"use server"
import { revalidateTag } from 'next/cache'
export default async function createComment(formData) {
try {
const resp = await fetch("create-api-url", {
method: 'POST',
headers: {
'Cookie': `PHPSESSID=${sessionId}`
},
body: formData
})
if (!resp.ok) {
throw new Error('Error creating comment')
}
data = await resp.json()
} catch (err) {
return {
error: err.message,
};
}
revalidateTag('comments')
}
When I submit a new comment, it gets saved in the database alrihgt but the comments data is not revalidated even after adding revalidateTag('comments')
to the createComment server action
. The correct data is only fetched after I refresh the page. What am I not doing right here and how do I correctly use revalidateTag()