Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 31 |
Tags
- 크로마DB
- expo 버전 오류
- 이미지처리
- langchain
- langgraph
- vllmmcp
- expo 아이폰 오류
- 리액트 네이티브
- nestjs시큐리티
- jotai
- expo 51 오류
- langchain react agent
- react
- 랭체인 툴
- langgraph mcp
- 상태관리
- 자바공부
- 타입스크립트상태관리
- 네스트시큐리티
- langchain tools
- expo 51 버전
- expo 안드로이드
- expo go 오류
- 리액트 네이티브 오류
- expo 아이폰
- AI
- VectorDB
- 스프링 공부
- comfyui
- rnn gnsfus
Archives
- Today
- Total
영리의 테크블로그
nest.js + react (jotai) 개발 [2] - jotai 비동기 처리 본문
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가 더 좋을까?
- 보일러플레이트 감소
- loading, error 상태 관리 자동화
- try-catch 로직 단순화
- 상태 공유 용이
- 여러 컴포넌트에서 같은 데이터 접근 가능
- 캐싱 자동 지원
- TypeScript 친화적
- 타입 추론이 자연스럽게 동작
- 타입 안정성 보장