영리의 테크블로그

nest.js + react (jotai) 개발 [2] - jotai 비동기 처리 본문

카테고리 없음

nest.js + react (jotai) 개발 [2] - jotai 비동기 처리

영리0 2024. 11. 19. 15:50

 

1. 비동기 Atom

기본적인 비동기 Atom

// 가장 심플한 비동기 atom
const asyncAtom = atom(async () => {
  const response = await fetch('https://api.example.com/data');
  return response.json();
});

 

redux + thunk 처럼 길지 않고 매우 편리한거 같음!

로딩/에러 상태 처리

const todoWithStatusAtom = atom(async (get) => {
  try {
    const data = await get(asyncAtom);
    return { status: 'success', data };
  } catch (error) {
    return { status: 'error', error };
  }
});

2. 실제 로그인 구현하기 

 

Auth Atom 만들기

interface LoginResponse {
    accessToken?: string;
}

interface LoginRequest {
    userId: string;
    userPassword: string;
}

// 인증 상태 저장용 atom
export const authAtom = atom<LoginResponse | null>(null);

// 로그인 처리용 atom
export const loginAtom = atom(
    (get) => get(authAtom),
    async (get, set, payload: LoginRequest) => {
        await axios.post<LoginResponse>('/auth/login', payload)
            .then((res) => {
                set(authAtom, res.data);
            })
    }
);

사용하기

function LoginComponent() {
    const [auth] = useAtom(authAtom);
    const [, login] = useAtom(loginAtom);

    const handleLogin = async () => {
        await login({
            userId: "user123",
            userPassword: "pass123"
        });
    }
}

3. useEffect vs Jotai 비동기 Atom

useEffect(() => {
    const fetchData = async () => {
        try {
            setLoading(true);
            const response = await axios.get('/api/data');
            setData(response.data);
        } catch (error) {
            setError(error);
        } finally {
            setLoading(false);
        }
    };

    fetchData();
}, []);

 

const dataAtom = atom(async () => {
    const response = await axios.get('/api/data');
    return response.data;
});

// 컴포넌트에서
const [data] = useAtom(dataAtom);

훨씬 짧아짐!

4. 왜 Jotai가 더 좋을까? 

  1. 보일러플레이트 감소
    • loading, error 상태 관리 자동화
    • try-catch 로직 단순화
  2. 상태 공유 용이
    • 여러 컴포넌트에서 같은 데이터 접근 가능
    • 캐싱 자동 지원
  3. TypeScript 친화적
    • 타입 추론이 자연스럽게 동작
    • 타입 안정성 보장