rndriver
v0.2.0
Published
React Native용 모듈
Maintainers
Readme
rndriver
React Native 앱을 위한 API 통신 및 상태 관리 모듈입니다.
기능
- 🔄 Axios 기반의 타입 안전한 API 클라이언트
- 📊 MobX를 활용한 상태 관리
- 🚨 예외 처리 및 Toast 알림 통합
- 🧪 테스트 가능한 비동기 코드 설계
- 📝 TypeScript 지원
설치
npm install rndriver
# 또는
yarn add rndriver기본 사용 방법
import React from "react";
import { View, Text, Button } from "react-native";
import { multiply, Example } from "rndriver";
// 함수 예제
function Demo() {
const [result, setResult] = React.useState(0);
const calculateResult = async () => {
try {
const value = await multiply(3, 7);
setResult(value);
} catch (error) {
console.error("계산 중 오류 발생:", error);
}
};
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>곱셈 결과: {result}</Text>
<Button title="계산하기" onPress={calculateResult} />
{/* Example 컴포넌트 사용 */}
<Example text="모듈에서 보내는 안녕하세요!" />
</View>
);
}API 클라이언트 및 상태 관리 설정
1. API 메소드 정의 파일 생성
// apiMethods.ts
import { ApiMethods } from "rndriver";
export const apiMethods: ApiMethods = {
auth: {
login: {
path: "/auth/login",
method: "POST",
},
register: {
path: "/auth/register",
method: "POST",
},
logout: {
path: "/auth/logout",
method: "POST",
},
refreshToken: {
path: "/auth/refresh",
method: "POST",
},
},
users: {
getProfile: {
path: "/users/profile",
method: "GET",
},
updateProfile: {
path: "/users/profile",
method: "PATCH",
},
},
};2. 에러 키 정의 파일 활용 (옵션)
// 필요한 경우 커스텀 에러 키 정의 확장
import { ErrorKey, ErrorMessages } from "rndriver";
export const CustomErrorKey = {
...ErrorKey,
// 추가 에러 키 정의
PAYMENT_FAILED: "PAYMENT_FAILED",
} as const;
export const CustomErrorMessages = {
...ErrorMessages,
// 추가 에러 메시지 정의
PAYMENT_FAILED: "결제가 실패했습니다. 다시 시도해주세요.",
};3. 앱에서 RNDriver 설정
// App.tsx
import React from "react";
import { createRNDriver } from "rndriver";
import { apiMethods } from "./apiMethods";
// API 클라이언트 및 스토어 생성
const { store, renderToastConfig } = createRNDriver(
"https://api.example.com",
apiMethods
);
function App() {
return (
<>
{/* 앱 컴포넌트 */}
<MainApp store={store} />
{/* Toast 컴포넌트는 앱의 최상위 레벨에 렌더링 */}
{renderToastConfig()}
</>
);
}
export default App;4. 컴포넌트에서 API 호출 및 상태 관리
// LoginScreen.tsx
import React, { useState } from "react";
import { View, TextInput, Button, Text } from "react-native";
import { observer } from "mobx-react-lite";
// 상태 관리 및 API 호출이 포함된 컴포넌트
const LoginScreen = observer(({ store }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleLogin = async () => {
const result = await store.login(email, password);
if (result) {
// 로그인 성공 시 처리
console.log("로그인 성공:", result);
}
};
return (
<View style={{ padding: 20 }}>
<TextInput
placeholder="이메일"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
style={{ marginBottom: 10, borderWidth: 1, padding: 10 }}
/>
<TextInput
placeholder="비밀번호"
value={password}
onChangeText={setPassword}
secureTextEntry
style={{ marginBottom: 20, borderWidth: 1, padding: 10 }}
/>
<Button
title={store.loading.login ? "로딩 중..." : "로그인"}
onPress={handleLogin}
disabled={store.loading.login}
/>
{store.errors.login && (
<Text style={{ color: "red", marginTop: 10 }}>
{store.errors.login}
</Text>
)}
</View>
);
});
export default LoginScreen;비동기 유틸리티 함수 사용
import { handleAsync } from "rndriver";
async function fetchData() {
const [error, data] = await handleAsync(
fetch("https://api.example.com/data")
);
if (error) {
console.error("데이터 로딩 실패:", error);
return null;
}
return data;
}테스트
# 모든 테스트 실행
yarn test
# 특정 테스트 파일 실행
yarn test Example.test.tsx
# 감시 모드로 테스트 실행
yarn test --watch개발
# 라이브러리 빌드
yarn build기여하기
리포지토리와 개발 워크플로우에 기여하는 방법은 기여 가이드를 참조하세요.
라이선스
MIT
