How to make multiple calls in one page with SWR nextjs hook?

Viewed 5700

I'd like to fetch 3 endpoints for one page, I'm using the SWR hook from next.js as I need to get it from the client side. The documentation doesn't help me as I have variables for the url in an other file. I'm new to this. Here is what I have and working well with just one endpoint:

data.ts

const fetcher = (url: string) => fetch(url).then((response) => response.json())

const getData = (endpoint: string) => {
  try {
    const { data, error } = useSWR(`${ENDPOINTS_URL}${endpoint}`, fetcher)
    return { data, error }
  } catch (error) {
    console.log('error:', error)
    throw error
  }
}

export const getData1 = () => getData(`endpoint1`)
export const getData2 = () => getData(`endpoint2`)
export const getData3 = () => getData(`endpoint3`)

And this is where I call them:

index.tsx

const { data, error } = getData1()
  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
1 Answers

Okay I got it!
Here is my solution (without the error):

data.ts

const getData = (endpoint: string) => {
  try {
    const { data } = useSWR(`${ENDPOINTS_URL}${endpoint}`, fetcher)
    return { data: data }
//...
}

export const getData1 = () => getData(`endpoint1`)

index.tsx

const { data: name1 } = getData1()
const { data: name2 } = getData2()

et voilĂ ! I hope it can help someone in the future :)

Related