useRecommendations.js

import useCocoApi from '../fetch/request';
import { shuffle } from '../../utility/common';
import { useEffect, useState } from 'react';
import useStickyState from '../common/useStickyState';

/**
 * Only shuffle post first load.
 * This allows to prefetch selected images for homepage.
 */
export default function useRecommendations() {
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState({});
  const [isFirstLoad, setIsFirstLoad] = useStickyState('isFirstLoad', true);
  const [data, error] = useCocoApi({
    path: `/use/recommendations`
  });

  useEffect(() => {
    if (data) {
      setIsFirstLoad(false);

      Object.keys(data).map((key) => {
        const list = isFirstLoad ? data[key].list : shuffle(data[key].list);

        result[key] = {
          ...data[key],
          list
        };
      });

      setResult(result);
      setLoading(!result.carousel && !error);
    }
  }, [data]);

  // TODO: make other hooks to return array instead of object
  // array doesnt enforce a name on the user
  return [result, error, loading];
}