2

I'm currently building my first JAM stack app using Nuxt as my front-end framework and Craft as my headless CMS. I'm leveraging Apollo as my GraphQL interface client. I have it pulling data back just fine, but I want to shuffle the output to always be random. I know I could do this in a typical twig query with .orderBy('RAND()') but I need a way to shuffle that with my GraphQL endpoint.

I know I can do this on the frontend by shuffling my <li>s or something, but would love for this to be more performant if I can help it.

I've tried a few variations of the below but can't seem to get it to work. Is this possible?

apollo: {
  entries: {
    query: stories,
    prefetch: true,
    variables: {
       "section": ["stories"],
       "orderBy": "RAND()"
    }
  }
},
  • This feels like it should work. Are you sure you are not hitting cached results? – Oli Apr 12 at 10:27
  • Hey Oli. Well I know RAND() is a PHP function. Maybe this isn't a Craft CMS question and more of an Apollo question? – Rob Erskine Apr 12 at 19:44
2

RAND() is the correct way to do this. (At least, it works in 3.5). One catch is that GraphQL queries are cached by default, so your results will always be returned in the same random order until your cache is invalidated. If you're using Nuxt with a static target, your entries will be displayed in the same order until the cache is expired and your app is regenerated.

Example of a working query:

{
  entries(section: "posts", orderBy:"RAND()") {
    title
    id
  }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.