Reputation: 31
In my nextJS app, I am using fetch API which collects data from mongoDB to fetch a list of participants.
In local developing environment, and production with Netlify it works well.
But in local production, and when I hosted on Vercel, it grams that are only on first call. Irrespective of I refreshes the page the data is not changed I have passed
{cache: no-cache}
inside fetch
but no luck. I also tried revalidate
as well. Can't find why. If it is something because of production the result would be similar in Netlify 😐
I am giving associated lines of codes here. But I can share my GitHub repository link if needed more context
const [participants, setParticipants] = useState([]);
const fetchParticipants = async () => {
try {
const fetchedParticipants = await fetchAllParticipants();
fetchedParticipants.sort((a, b) => a.serial - b.serial);
setParticipants(fetchedParticipants);
} catch (error) {
console.log(error);
}
};
// const [participant, setParticipant] = useState<IndexState['participant']>('')
useEffect(() => {
fetchParticipants();
}, []);
actions/index.js
export const fetchAllParticipants = async () => {
try {
const response = await fetch("api/participants/all", {
cache: 'no-cache', // don't cache
});
const data = await response.json();
//console.logdata.allParticipants, " are all participants");
return data.allParticipants;
} catch (error) {
console.log(error);
}
};
app/api/participants/all/route.js
import connectToDb from '@utils/connectToDb'
import Participant from '@models/Participant'
export const GET = async () => {
try {
await connectToDb()
const allParticipants = await Participant.find()
// console.log(allParticipants, ' inside GET')
return new Response(JSON.stringify({allParticipants,success: true, status: 200}))
} catch (error) {
console.log(error, ' error in route GET');
return new Response(JSON.stringify({error}), {success: false, status:405})
}
}
Please assist in finding what cause this.
I used next js 13.8 and 14 but they are not having any difference.
Thanks in advance
tried passing cache related options in fetch but got no result.
On searching internet I haven't found this problem discussed.
Upvotes: 2
Views: 2152
Reputation: 41
export const dynamic = "force-dynamic";
^ Add this to the top of your route.ts
Upvotes: 2