0

I asked a question here about how to get 20 random items from that JSON and I used one of the answers like this:

  const a = Myjson;
  useEffect(() => {
    for (let i = a.length; i-- > 0; ) {
      const j = Math.floor(Math.random() * i); // 0 ≤ j ≤ i
      [a[i], a[j]] = [a[j], a[i]];
    }
  }, []);
    
    {a
      .slice(0, 20)
      .map((item) => (
        <Link
          href={item.ud}
          key={item.id}
        >
         {item.test}
        </Link>
      ))}

There is a problem that when I refresh I see the ordered 20 items of that JSON and then suddenly it changes to random 20 items; how can I fix the code so when I refresh I can only see the random 20 items without seeing those ordered items?

frg
  • 45
  • 3

1 Answers1

1

Instead of useEffect to update the ordering after the first render, you could useState to provide a consistent (random) ordering generated on the first render:

  const [a] = useState(() => {
    // Same code as in your useEffect, but with `a` renamed for clarity
    let b = [...Myjson];  // take a copy of the array
    for (let i = b.length; i-- > 0; ) {
      const j = Math.floor(Math.random() * i); // 0 ≤ j ≤ i
      [b[i], b[j]] = [b[j], b[i]];
    }
    return b;  // Return value is used as the state value
  });

  // ... rendering code as before

useState will run the initialisation code the first time the component is rendered. Although useState also returns a setter, you don't need to use it if you just want to persist a particular value between renders.

motto
  • 2,888
  • 2
  • 2
  • 14