
- Zustand 상태의 구조를 정의하는 인터페이스
interface PostState { postId: string | null; post: Post | null; postArea: string | null; setPostId: (id: string | null) => void; setPost: (post: Post | null) => void; setPostArea: (area: string | null) => void; fetchPost: (id: string) => Promise<void>; }postId: 현재 선택된 게시물의 ID를 저장하는 상태 post: 현재 선택된 게시물의 전체 데이터 postArea: 게시물과 연관된 지역 정보를 저장 setPostId, setPost, setPostArea: 각각의 상태를 업데이트하기 위한 메서드 fetchPost: Supabase에서 게시물 데이터를 가져오는 비동기 함수
- Zustand 스토어 생성
const usePostStore = create<PostState>((set) => ({ postId: null, post: null, postArea: null, setPostId: (id) => set({ postId: id }), setPost: (post) => set({ post }), setPostArea: (area) => set({ postArea: area }), fetchPost: async (id: string) => { const supabase = createClient(); const { data, error } = await supabase .from('posts') .select( ` *, schedule (area) ` ) .eq('id', id) .single(); if (error) { console.error('Error fetching post:', error); } else { const scheduleData = data.schedule ? data.schedule[0]?.area || 'N/A' : 'N/A'; set({ post: data, postArea: scheduleData, }); } } }));postId | post | postArea : 이 세 가지 상태를 초기화. 초기 상태는 모두 null로 설정
setPostId | setPost | setPostArea : 이 세 가지 상태를 업데이트
fetchPost 메서드: createClient를 사용하여 Supabase 클라이언트를 생성 Supabase에서 특정 id에 해당하는 게시물 데이터를 가져옴 데이터가 성공적으로 받아지면, post와 postArea 상태를 업데이트 오류가 발생하면, 콘솔에 오류 메시지를 출력
요약
- URL 파라미터 가져오기
export default function DetailImg({ isWeb }: WebProps) { const { id } = useParams(); const postId = Array.isArray(id) ? id[0] : id;useParams로 id 가져오기: URL에서 id 파라미터를 가져옴 postId 처리: id가 배열일 수 있기 때문에, postId를 단일 값으로 처리하여 사용
- Zustand 상태와 메서드 가져오기
const { setPostId, post, fetchPost } = usePostStore((state) => ({ setPostId: state.setPostId, post: state.post, fetchPost: state.fetchPost }));usePostStore: Zustand 상태 관리에서 setPostId, post, fetchPost를 가져옴 setPostId: 상태에 postId를 설정하는 함수 post: 현재 상태에 저장된 게시물 데이터 fetchPost: Supabase에서 게시물 데이터를 가져오는 비동기 함수
- useEffect를 사용하여 데이터 가져오기
useEffect(() => { if (postId) { setPostId(postId); fetchPost(postId); } }, [postId, setPostId, fetchPost]);useEffect: 컴포넌트가 처음 렌더링될 때와 postId, setPostId, fetchPost 값이 변경될 때마다 호출됨 postId가 존재하면, setPostId를 호출하여 postId를 상태에 저장하고, fetchPost를 호출하여 해당 게시물의 데이터를 가져옴
요약
투어 상세 내용과 태그도 위와 비슷한 방식이기 때문에 생략하도록 하겠다❗️
(글이 너무 길어지는 거 같아서...🥹 )
