0

I really don't understand why I can't get useSWR to work in my app. I have been trying for two days and can't seems to find the reason. The normal fetch works fine calling the same address in the same function.

const address =server+ `/api/google/getData?term=` + endRow.name;
const fetcher = async (url) => await axios.get(url).then((res) => res.data);
const { data, error } = useSWR(address, fetcher);
//Always undefined
console.log(data)
//Gets the data
async function test() {
    const res = await fetch(address)
    console.log(await res.json())
}
test();

API method:

import { connectToDatabase } from '../../../util/mongodbUtil'

export default async (req, res) => {
  const { db } = await connectToDatabase();
  return new Promise(async (resolve, reject) => {
    try{
      res.status(201).json({ response: ["TESTDATA"], success: true })
      resolve()
    } catch (e) {
      console.log(e)
      res.status(400).json({ success: false })
      resolve()
    }
  })
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Marcus Vr
  • 1
  • 2
  • `useSWR` is an async method and you are not awaiting it, so of course when you do `console.log` directly after the call, it's not finished yet ... – derpirscher Jan 21 '22 at 14:22
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – derpirscher Jan 21 '22 at 14:23
  • So I have tried async function test() { const { data, error } = await useSWR(address, fetcher); console.log(await data) } test(); But still no data, should I not get "in promise" message if a promise is not awaited? – Marcus Vr Jan 21 '22 at 15:03
  • `useSWR` is a hook, while it does have asynchronous operations happening it doesn't need to be awaited. – juliomalves Jan 22 '22 at 11:51

1 Answers1

2

in _app configure your SWR

<SWRConfig value={{
           refreshInterval: 0,
           fetcher: (url: string, token: string) => fetch(url, {
             headers: token ? {Authorization: token} : undefined
           }).then((res) => res.json())
}}>
...
<Component {...pageProps} />

then you can use const {data, error} = useSWR([requestedUrl, token])

M-Raw
  • 779
  • 4
  • 10