Next.js Discord

Discord Forum

fetching data locally

Answered
Petrov posted this in #help-forum
Open in Discord
Avatar
Hello Community!

I have deployed my app in Vercel and I am struggling to fetch my data from MongoDB (which is working locally).
I really think it's something simple but after reading the docs and checking some examples I can't tell what's the issue.

The following code contains the problematic data fetch (I assume that fixing this will resolve the other case where data fetching doesn't work):
// On mount fetch the list of all Todos from the Mongo database useEffect(() => { const controller = new AbortController(); const signal = controller.signal; async function getTodos() { const options = { method: "GET", url: "/api/todos", signal, }; try { const response = await axios.request(options); if (response.statusText !== "OK") { throw new Error("Failed to fetch Todos"); } const todos = response.data.todos; // Set the state so the list can be displayed to the user setTodosArray([...todos]); } catch (error) { console.log(error); } } getTodos(); return () => { // Cleanup function controller.abort(); }; }, []);

In Vercel it throws the "Failed to fetch Todos" error that is thrown if the response status is not OK. I also see that the Integration is properly set in Vercel and the MONGODB_URI env variable was automatically added when the setup was complete.
Thank you for the assistance in advance!
Answered by Ray
maybe try this instead
   if (response.status !== 200) {
    throw new Error("Failed to fetch Todos");
  }
View full answer

14 Replies

Avatar
Yes, it gives me the proper data
Image
Avatar
@Petrov Yes, it gives me the proper data
Avatar
is this from the app on vercel or locally?
Avatar
It's from the app on Vercel when I used https://<my-vercel-url>/api/todos.
Avatar
then it should work
could you share the url?
It even works when I run it in the console...
Image
Avatar
maybe try this instead
   if (response.status !== 200) {
    throw new Error("Failed to fetch Todos");
  }
Answer
Avatar
i can see the data
Image
Avatar
statusText is blank or unsupported with http/2
the reason why it works on localhost is when you are fetching locally, it use http/1.1
Avatar
Wow, can't believe it was this. It now works! Also it rendered an empty list even though I have data in the collection but it turns out that during deployment a new collection is added.
Thank you very much for the help Ray!
Avatar
np