import useSWR from 'swr';
import { api } from '../api/client';

export function useResources() {
  const { data, error, isLoading, mutate } = useSWR('/resources', async () => {
    const { data, error } = await api.resources.get();
    if (error) throw error;
    return data;
  });

  return {
    resources: data,
    isLoading,
    isError: error,
    mutate
  };
}

export function usePosts() {
  const { data, error, isLoading, mutate } = useSWR('/posts', async () => {
    const { data, error } = await api.posts.get();
    if (error) throw error;
    return data;
  });

  return {
    posts: data,
    isLoading,
    isError: error,
    mutate
  };
}

export function usePost(id: string) {
  const { data, error, isLoading, mutate } = useSWR(id ? `/posts/${id}` : null, async () => {
    const { data, error } = await api.posts({ id }).get();
    if (error) throw error;
    return data;
  });

  return {
    post: data,
    isLoading,
    isError: error,
    mutate
  };
}
