All files / src/lib/store/metadata useMetadata.ts

0% Statements 0/13
0% Branches 0/4
0% Functions 0/4
0% Lines 0/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                                                                       
'use client';
 
import { useQuery } from '@apollo/client/react';
import { useEffect } from 'react';
import { GET_ALL_METADATA } from '@/lib/graphql/queries';
import { useAppDispatch } from '../store';
import type { Metadata } from './metadata';
import { setMetadata, setMetadataError, setMetadataLoading } from './metadata';
 
interface GetAllMetadataResponse {
  getAllMetadata: Metadata[];
}
 
/**
 * Custom hook to fetch and manage metadata in Redux store
 * Fetches metadata from GraphQL API and populates Redux store
 * Should be called once at app initialization
 */
export const useFetchMetadata = () => {
  const dispatch = useAppDispatch();
 
  const { data, loading, error, refetch } = useQuery<GetAllMetadataResponse>(
    GET_ALL_METADATA,
    {
      fetchPolicy: 'cache-first', // Use cache if available, otherwise fetch
      notifyOnNetworkStatusChange: true,
    },
  );
 
  useEffect(() => {
    dispatch(setMetadataLoading(loading));
  }, [loading, dispatch]);
 
  useEffect(() => {
    if (data?.getAllMetadata) {
      dispatch(setMetadata(data.getAllMetadata));
    }
  }, [data, dispatch]);
 
  useEffect(() => {
    if (error) {
      dispatch(setMetadataError(error.message));
    }
  }, [error, dispatch]);
 
  return {
    loading,
    error,
    refetch,
  };
};