score:1

Accepted answer
import { useEffect, useMemo, useState } from 'react';

const DEFAULT_PROJECTS = [
  { project_id : 123, name: 'p1' },
  { project_id : 1234, name: 'p2' },
];

const useProjects = () => {
  const [dataFromApi, setDataFromApi] = useState(null);

  useEffect(() => {
    if (!!dataFromApi) return;

    // Simulate the data fetch
    const fetchData = async () => {
      return new Promise(resolve => {
        setTimeout(() => {
          const map = new Map();
          map.set(123, { 
            field3: 'api data',
            field4: 'other data',
          });

          setDataFromApi(map);
        }, 2000);
      });
    };

    fetchData();
  }, [dataFromApi]);

  return useMemo(() => {
    let extraData = dataFromApi || new Map();

    return DEFAULT_PROJECTS.map(proj => {
      const extraFields = extraData.get(proj.project_id) || {};

      return {
          ...proj,
          ...extraFields,
      };
    });
  }, [dataFromApi]);
}

export default useProjects;

Related Query

More Query from same tag