Cant fetch data with new App Router API
Answered
Russian Blue posted this in #help-forum
Russian BlueOP
Just made a new next js 13 app with the new app router api. Here is my code
What's going on here? The suspense works but then I am expecting a big blob of an object dropped on the homepage.
I'm aware I'm not using
import { Suspense } from 'react'
export default async function Home() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Display />
</Suspense>
)
}
const Display = async () => {
const data = (await fetch('https://my-json-server.typicode.com/typicode/demo/posts', { cache: 'no-store' }))
return <div>
{JSON.stringify(data)}
</div>
}What's going on here? The suspense works but then I am expecting a big blob of an object dropped on the homepage.
I'm aware I'm not using
.json(), but that doesn't work either (and either way, I should be seeing an object)Answered by joulev
yes
const res = await fetch(...)
const data = await res.json()
// then you get the data15 Replies
Russian BlueOP
Yes, you too? '
@Russian Blue Yes, you too? '
this is not a bug
you are simply using fetch wrong
if you want to get text response, use
await data.text()Russian BlueOP
I just changed the URL btw to something that doesn't have cors policies.
My mistake
My mistake
if you want to get json response, use
await data.json()this is not related to nextjs, just normal
fetch usageyou are using
fetch wrong so you get wrong resultscors is irrelevant here because the fetch is run on the server
Russian BlueOP
I'm used to axios. So fetch returns a promise to another promise?
yes
const res = await fetch(...)
const data = await res.json()
// then you get the dataAnswer
Russian BlueOP
Oh or .json returns a promise
I see, thank you