import { useQuery, useQueryClient } from '@tanstack/react-query';
import React from 'react';

export const useGlobalState = <T>(key: any[], initialData: T) => {
  const queryClient = useQueryClient();
  const stateQueries = useQuery<T>(
    key,
    () => Promise.reject('This thing never happens.'),
    {
      initialData,
      staleTime: Infinity,
      cacheTime: Infinity,
    },
  );

  const setData = React.useCallback(
    (param: React.SetStateAction<T>) => {
      const oldState = queryClient.getQueryData<T>(key);
      queryClient.setQueryData(
        key,
        typeof param === 'function' ? (param as Function)(oldState) : param,
      );
    },
    [queryClient, key],
  );

  return {
    setData,
    data: stateQueries.data,
  };
};
