## 프로젝트 개요
모바일 앱에서 오프라인 상태에서도 데이터를 저장하고, 네트워크 복구 시 서버와 동기화하는 기능을 구현합니다. 이는 불안정한 네트워크 환경에서 사용자 경험 향상을 위한 핵심 기능입니다.
## 주요 기능
- AsyncStorage를 통한 로컬 데이터 저장
- 오프라인 상태 감지 및 자동 동기화
- 네트워크 오류 시 유저 알림 처리
- 데이터 불일치 시 재시도 로직 포함
- 간단한 UI로 노트 관리 기능 구현
## 사용 방법
1. Expo CLI를 통해 프로젝트 생성 후 실행
2. AddNoteScreen에서 노트 추가 후 오프라인 상태로 전환
3. 네트워크 복구 시 자동 동기화 확인
4. 서버 에러 시 알림 메시지 표시 확인
## 확장 가능성
- Firebase Realtime Database 연동
- 데이터 충돌 해결 로직 추가
- 실시간 동기화 기능 구현
⚛️ 오프라인 데이터 관리 및 네트워크 동기화 실현 예제
React Native 예제
중급
난이도
예제
타입
10/31
등록일
오프라인 데이터 관리 및 네트워크 동기화 실현 예제
중급태그
코드 예제
import React, { useEffect, useState } from 'react';
import { View, Text, TextInput, Button, Alert, Platform } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import NetInfo from '@react-native-community/netinfo';
const App = () => {
const [notes, setNotes] = useState([]);
const [newNote, setNewNote] = useState('');
const [isOnline, setIsOnline] = useState(true);
// 네트워크 상태 감지
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsOnline(state.isConnected || state.type === 'wifi');
});
return () => unsubscribe();
}, []);
// 로컬 데이터 불러오기
useEffect(() => {
const loadNotes = async () => {
try {
const storedNotes = await AsyncStorage.getItem('notes');
if (storedNotes) setNotes(JSON.parse(storedNotes));
} catch (error) {
console.error('데이터 로드 실패:', error);
}
};
loadNotes();
}, []);
// 노트 저장 함수
const saveNote = async () => {
if (!newNote.trim()) return;
const updatedNotes = [...notes, { id: Date.now(), text: newNote }];
try {
await AsyncStorage.setItem('notes', JSON.stringify(updatedNotes));
setNotes(updated, setNewNote('');
} catch (error) {
Alert.alert('저장 실패', '데이터를 로컬에 저장하는 중 오류가 발생했습니다.');
}
};
// 서버 동기화 함수 (모의 API)
const syncWithServer = async () => {
if (!isOnline) {
Alert.alert('네트워크 없음', '인터넷 연결이 되어 있지 않습니다. 다시 시도해 주세요.');
return;
}
try {
// 실제 API 호출 로직 구현
await new Promise(resolve => setTimeout(resolve, 1500));
Alert.alert('동기화 완료', '서버와 데이터를 성공적으로 동기화했습니다.');
} catch (error) {
Alert.alert('동기화 실패', '서버와 데이터를 동기화하는 중 오류가 발생했습니다. 다시 시도해 주세요.');
}
};
return (
<View style={{ padding: 20, flex: 1, backgroundColor: '#f5f5f5' }}>
<Text style={{ fontSize: 24, marginBottom: 20 }}>오프라인 노트 관리</Text>
<TextInput
placeholder="새로운 노트 입력"
value={newNote}
onChangeText={setNewNote}
multiline
style={{ borderWidth: 1, padding: 10, marginBottom: 15, borderRadius: 8 }}
/>
<Button title="저장" onPress={saveNote} disabled={!newNote.trim()} />
<Button title="서버 동기화" onPress={syncWithServer} style={{ marginTop: 10 }} />
<Text style={{ marginTop: 20, fontSize: 18 }}>총 {notes.length}개 노트</Text>
</View>
);
};
export default App;
등록일: 2025년 10월 31일 02:37
언어 정보
언어
React Native
카테고리
Mobile
인기도
#29
학습 팁
코드를 직접 실행해보세요
변수를 바꿔가며 실험해보세요
오류가 나도 포기하지 마세요
다른 예제도 찾아보세요