Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Tags
more
Archives
Today
Total
관리 메뉴

훈돌라

2024. 6. 19. 아웃소싱 프로젝트 3일차 본문

카테고리 없음

2024. 6. 19. 아웃소싱 프로젝트 3일차

훈돌라 2024. 6. 19. 22:20

 

 

 

 

supabase /table/ recipes / thumbnail 에 들어갈 이미지를 public url 로 변환 완료 (기존은 base64)

 

 //레시피 추가 메서드
  async postRecipe(recipe, file, userId, nickname) {
    let thumbnailUrl = ''; // 기본적으로 빈 문자열 또는 기본 이미지 URL로 설정
    // 파일이 있는 경우에만 이미지 업로드 시도
    if (file) {
      // 스토리지에 이미지 저장
      const { data: uploadData, error: uploadError } = await supabase.storage
        .from('images')
        .upload(`recipeimages/${recipe.id}.${file.name.split('.').pop()}`, file, {
          cacheControl: '3600',
          upsert: false
        });

      if (uploadError) {
        console.error('Error uploading image:', uploadError);
        return;
      }

      // 저장된 이미지를 다시 URL로 불러오기
      const { data: reloadData, error: reloadError } = await supabase.storage
        .from('images')
        .getPublicUrl(`recipeimages/${recipe.id}.${file.name.split('.').pop()}`);

      if (reloadError) {
        console.error('Error getting public URL:', reloadError);
        return;
      }

      thumbnailUrl = reloadData.publicUrl;
    }
    console.log('Inserting recipe with data:', {
      id: recipe.id,
      title: recipe.title,
      user_id: userId,
      nickname: nickname,
      content: recipe.content,
      thumbnail: thumbnailUrl
    });
    // 레시피 데이터베이스에 추가
    const { data, error } = await supabase.from('recipes').insert({
      id: recipe.id,
      title: recipe.title,
      user_id: userId,
      nickname: nickname,
      content: recipe.content,
      thumbnail: thumbnailUrl
    });

    if (error) {
      console.error('Error inserting recipe:', error);
    } else {
      console.log('Recipe inserted successfully:', data);
    }
  }

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import api from '../../../api/api';

export const useGetRecipes = () => {
  const queryClient = useQueryClient();
  return useQuery({
    queryKey: ['recipes'],
    queryFn: async () => {
      const data = await api.recipe.getRecipes();
      return data;
    },
    onSuccess: () => queryClient.invalidateQueries(['recipes'])
  });
};

export const useRecipeDetail = (recipeId) => {
  const queryClient = useQueryClient();
  return useQuery({
    queryKey: ['recipeDetail', recipeId],
    queryFn: async () => {
      const data = await api.recipe.getRecipeById(recipeId);
      return data;
    },
    onSuccess: (data) => queryClient.invalidateQueries(['recipeDetail', recipeId], data),
    enabled: !!recipeId
  });
};

export const useCreateRecipe = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data) => {
      const { recipe, file, userId, nickname } = data;
      await api.recipe.postRecipe(recipe, file, userId, nickname);
    },
    onSuccess: () => queryClient.invalidateQueries(['recipes']),
    onError: (error) => {
      console.error('레시피 생성 도중 에러 발생:', error);
    }
  });
};

export const useUpdateRecipe = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ recipe, file }) => {
      const data = await api.recipe.UpdateRecipe(recipe, file);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['recipes']);
    },
    onError: (error) => {
      console.error('레시피 업데이트 도중 에러 발생:', error);
    }
  });
};

export const useDeleteRecipe = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (recipe) => {
      const data = await api.recipe.DeleteRecipe(recipe);
      return data;
    },
    onSuccess: () => queryClient.invalidateQueries(['recipes']),
    onError: (error) => {
      console.error('레시피 삭제 도중 에러 발생:', error);
    }
  });
};

 

 

tanstack querie 를 사용하여 createRecipe, updateRecipe, deleteRecipe (supabase) 관리

 

아직 새로운 라우터 + 리액트 쿼리 + 슈퍼베이스에 익숙하지 않아서 컴포넌트를 어떻게 분리해야 할지 감을 못 잡아
CommitRecipe 에 (페이지 이름 변경 예정) 조금 지저분하게 코드들을 작성 해뒀는데, 종하(나의 리더) 님이 깔끔하게 컴포넌트로 분리 해봐도 좋을 것 같다고 하셔서 바로 진행 해보려고 한다.

프로젝트가 끝나고 금~일 동안은 라우터 + 리액트 쿼리 + 주스탠드 + 슈퍼베이스를 집중적으로 공부 해야겠다.
(겸사겸사 tailwind)