6

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>
Akihito KIRISAKI
  • 1,243
  • 6
  • 12
Liam
  • 221
  • 1
  • 3
  • 7

1 Answers1

9

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 :)

Liam
  • 221
  • 1
  • 3
  • 7
  • This breaks the rules of hooks... no? https://legacy.reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions – daCoda Jun 19 '23 at 01:39