API unsplash.com random take a long time first render

Viewed 299

I'm using production Unsplash API, fetching random photo from my collection. The first render takes 30-40sec to load. The API response is pretty fast, but then took long time to load. I found just one other similar topic around, here on SO: Hotlinked images render insanely slow with React and Webpack

I add width and height to my query but still, no luck, is still very slow at first render. Anyone experience the same and found a solution?

That's an example of API endpoint I call:

https://api.unsplash.com/photo/random/?collection=MY_COLLECTION_ID&q=85&w=1080&h=800

That's the code to fetch:

/**
 * Calculate width to fetch image, tuned for Unsplash cache performance.
*/
export function calculateWidth(screenWidth: number = 1920): number {
  // Consider a minimum resolution too
  screenWidth = Math.max(screenWidth, 1080); // Lower limit at 1080
  screenWidth = Math.min(screenWidth, 3840); // Upper limit at 4K
  screenWidth = Math.ceil(screenWidth / 240) * 240; // Snap up to nearest 240px for improved caching
  return screenWidth;
}


export const fetchRandomPhoto = async function () {
  const url = `${process.env.UNSPLASH_API_URL}/photos/random/`
  const width = calculateWidth(window.innerWidth);

  const params = new URLSearchParams({
    collections: `${process.env.UNSPLASH_COLLECTION_ID}`,
    q: '85', // range [0-100]
    w: `${width}`,
    h: '800'
  })

  const headers = new Headers({
    Authorization: `Client-ID ${process.env.UNSPLASH_API_KEY}`,
  })

  let dailyPhoto = localStorage.getItem('dailyPhoto')
  const savedPhotoDate = localStorage.getItem('savedPhotoDate')


  if (!dailyPhoto) {
    try {
      const res = await fetch(`${url}?${params}`, { headers })

      if (res.ok) {
        dailyPhoto = await res.json()
        localStorage.setItem('dailyPhoto', JSON.stringify(dailyPhoto))

        return dailyPhoto
      } else {
        console.log('Error fetching unsplash photo')
        return FALLBACK_PHOTO
      }
    } catch (err) {
      console.log('Error fetching unsplash server', err)
      return FALLBACK_PHOTO
    }
  } else {
    return JSON.parse(dailyPhoto)
  }
}

0 Answers
Related