#Data Fetching and then Randomizing in Next.js

9 messages · Page 1 of 1 (latest)

lofty gyro
#

Basically, I created a little api route in the nextjs directory which returns a list of strings and I want to randomly display them on screen but I am unable to do so... How should I go about solving this?

This is my index.js

import useSWR from 'swr'

export default function Home() {

  const{ data, error } = useSWR('./api/stuff')
  if (error) {
    return <div>Failed to load stuff</div>
  }

  if (!data) {
    return <div>Loading the stuff...</div>
  }

  function randomizeThestuff(data) {
    return data[Math.floor(Math.random() * data.length)];
  }

  return (
    <h1 className="text-3xl font-bold underline">
      randomizeThestuff(data)
    </h1>
  )
}

This is my /api/stuff.js file

const stuff = [
  "value",
  "value",
  "etc",
]

export default function handler(req, res) {
  res.status(200).json(
      stuff
  )
}

and my browser is showing this

open fossil
#
  1. the URL to your api route seems to be incorrect, it shouldn't start with a dot, try /api/stuff instead
#
  1. the final JSX is rendering "randomizeThestuff(data)" as plain text, in React if you want to evaluate an expression you need to wrap it with {}:
<h1>{randomizeThestuff(data)}</h1>
#
  1. in this specific situation (client-side fetching) it is not a fatal error but you shouldn't have components with nondeterministic renders: every time Home is rendered with the same inputs it should render the same thing, which is not the case because on every render it could render a different new item
#

this situation is not very simple because your items are only loaded once the fetch is complete, so you would also need to have an useEffect hook to update the random index when the data is changed

lofty gyro
#

or would there be a way for me to just randomize the return response in the api itself so I don't have to deal with that hassle in the frontend?

open fossil