How to randomize posts in state

As I understand, by default, it’s not possible to get random results from wp-json. Maybe this isn’t so bad either, because I would like the results to be cached. But how can I randomize fetched data in Frontity?

This is a component I’m using:

const Team = ({ state, actions, libraries }) => {
   // 1. fetch data from the post type
   useEffect(() => {
      actions.source.fetch("/team/");
   });

   // 2. get data from frontity state
   const data = state.source.get("/team/");

   if (data.isReady && !data.isError) {

      return (
         <>
            <h1>Team</h1>
            <MemberContainer>
               {
                  data.items.map(({ type, id }, index) => {
                     const item = state.source[type][id];
                     // Render one Item component for each one.
                     return <Member item={item} />;

                  })
               }
            </MemberContainer>
         </>
      );
   }

   if (data.isError) {
      console.log(data);
   }

   return null;
}

And I tried using something like this, before the return statement:

data.items.sort(() => Math.random() - 0.5);

But when doing that, I get the following error in my Terminal:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

So I guess that I’m not handling this the way I should, but what would be the correct approach?

Hi @dominique

I don’t have your data to work with so haven’t tested this, but I think I would use data.items.map before the return statement to get the id’s of the posts into an array and then randomise that array. You could then iterate over the array of id’s to perform the action you want with the corresponding member of the data array.

I hope I’ve understood your issue correctly.

Hi @mburridge,

Thanks for your suggestion. The shuffling works fine, but something very weird happens to the FeaturedMedia element in the Member component. The shown image doesn’t match the item, it’s from another one. This happens even though the passed ID of the featured image is actually correct.

I can see an error in the console:
Warning: Prop alt did not match. Server: "NIJ-portret-Jean_Paul-2" Client: "dominique"

This is what I did:

const shuffledData = data.items.map((a) => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map((a) => a.value)

const slides = [];

shuffledData.map(({ type, id }, index) => {
   const item = state.source[type][id];
   // Render one Item component for each one.
   slides.push(<Member item={item} />);
});

I reckon this doesn’t only happen with my data, but always. However, if you’d like to test with my data, you can clone my repo: https://bitbucket.org/noesteijver/frontity/src/master/, the template-part is called team.js.