[Next js] 패치 비동기 함수에서 유저아이디가 안가져오는 문제(null, undefind)

임보라·2024년 10월 25일

Next.js

목록 보기
13/23

userId는 잘 전해졌는데 계속 null 또는 undefind로 뜨는 문제

fetchStampActive.ts 패치 비동기 함수

//로그인유저의 스템프 항목 전부 + 스탬프 활성화된 데이터만
export const fetchStampActive = async (userId: string) => {
  const { data, error } = await browserClient.from('stamp').select('*').eq('user_id', userId).eq('visited', true);
  if (error) {
    console.error('가져오기 오류1:', error.message);
  }
  return data;
};

StampList 컴포넌트(BE)

수정01_
queryFn: () => fetchStampActive(userId!)
-> null이 아님을 보장하는 ! 사용

'use client';
...
import { fetchStampActive } from '@/server/fetchStampList';

const StampList = () => {
  const [userId, setUserId] = useState<string | null>(null);

  useEffect(() => {
    //유저아이디 가져오기
  }, []);

  const {
    data: stampList,
    isLoading,
    error
  } = useQuery({
    queryKey: ['stamp'], //고유키
    queryFn: () => fetchStampActive(userId!),
  });
};

export default StampList;

수정02
enabled: !!userId
-> enabled: userId가 있을 때만 쿼리 실행
해결X : undefind 로 불러와짐.._

queryKey: ['stamp'], 
queryFn: () => fetchStampActive(userId!),
enabled: !!userId // userId가 있을 때만 쿼리 실행

수정03_
-> 비동기문제인거같아 똑같이 async/await 붙여줌
-> userId값이 있는경우, 없는경우의 if문 추가

StampList 컴포넌트(AF) - 수정 완료

'use client';
...
import { fetchStampActive } from '@/server/fetchStampList';

const StampList = () => {
  const [userId, setUserId] = useState<string | null>(null);

  useEffect(() => {
    //유저아이디 가져오기
  }, []);

  const {
    data: stampList,
    isLoading,
    error
  } = useQuery({
    queryKey: ['stamp'], //고유키
    queryFn: async () => {
      if (userId) {
        return await fetchStampActive(userId);
      } else {
        return null;
      }
    },
    enabled: !!userId // userId가 있을 때만 쿼리 실행
   enabled: !!userId // userId가 있을 때만 쿼리 실행
  });
};

export default StampList;

0개의 댓글