framework/ReactNative

갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편17 – 사용자 맞춤 통계 대시보드 만들기 (로그인 기반 필터 적용)

octo54 2025. 5. 26. 10:23
반응형

갓난애기도 배울 수 있는 React Native 가이드 ⏺️ 보너스편17 – 사용자 맞춤 통계 대시보드 만들기 (로그인 기반 필터 적용)

지난 편에서는 모든 알림 기록을 종합하여
요일별, 날짜별, 유형별 통계를 시각화하는 대시보드를 만들었습니다.
하지만 다수의 사용자가 사용하는 앱이라면
**"각 사용자에게 맞춤 통계"**를 보여주는 것이 훨씬 더 가치 있겠죠?

이번 글에서는 Firebase Authentication과 Firestore를 연동하여
로그인한 사용자 기준으로 알림 통계를 필터링하는 방법을 알아봅니다. 🔐📊


✅ 1. 목표 기능 요약

기능 설명

사용자 로그인 연동 Firebase Auth를 통해 유저 인증 구현
유저별 알림 분리 저장 알림 전송 시 사용자 ID(userId) 함께 저장
유저별 통계 필터링 로그인한 사용자 기준으로 Firestore 데이터 쿼리 필터링
통계 대시보드 개인화 해당 유저의 통계만 Victory 차트에 시각화

✅ 2. Firebase Auth 설정

  1. Firebase Console → Authentication 활성화
  2. 이메일/비밀번호 로그인 방식 추가
  3. Firebase SDK 설치 (이미 되어 있다면 생략)
npm install @react-native-firebase/auth

✅ 3. 로그인 화면 구성 (LoginScreen.js)

import React, { useState } from 'react';
import { View, TextInput, Button, Alert, StyleSheet } from 'react-native';
import auth from '@react-native-firebase/auth';

export default function LoginScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const login = async () => {
    try {
      await auth().signInWithEmailAndPassword(email, password);
      navigation.replace('AlarmDashboard'); // 로그인 성공 시 이동
    } catch (err) {
      Alert.alert('로그인 실패', err.message);
    }
  };

  return (
    <View style={styles.container}>
      <TextInput placeholder="이메일" value={email} onChangeText={setEmail} style={styles.input} />
      <TextInput placeholder="비밀번호" value={password} secureTextEntry onChangeText={setPassword} style={styles.input} />
      <Button title="로그인" onPress={login} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 20 },
  input: { borderWidth: 1, marginBottom: 10, padding: 10 },
});

✅ 4. 알림 기록 시 유저 ID 저장 (NotificationService.js)

반응형
import auth from '@react-native-firebase/auth';

export const logAlarmSend = async (title, message) => {
  const token = await messaging().getToken();
  const userId = auth().currentUser?.uid || 'guest';

  return firestore().collection('alarm_logs').add({
    title,
    message,
    token,
    userId,
    sentAt: firestore.FieldValue.serverTimestamp(),
  });
};

✅ 5. 사용자 기준 통계 데이터만 조회 (수정된 fetchAlarmStats)

import auth from '@react-native-firebase/auth';

export const fetchAlarmStats = async () => {
  const userId = auth().currentUser?.uid;
  if (!userId) return { byDay: {}, byDate: {}, byType: {} };

  const snapshot = await firestore()
    .collection('alarm_logs')
    .where('userId', '==', userId)
    .orderBy('sentAt', 'desc')
    .limit(100)
    .get();

  const data = snapshot.docs.map(doc => doc.data());

  const result = { byDay: {}, byDate: {}, byType: {} };
  data.forEach(log => {
    const date = moment(log.sentAt?.toDate());
    const day = date.format('dddd');
    const dateStr = date.format('YYYY-MM-DD');
    const type = log.type || 'unknown';

    result.byDay[day] = (result.byDay[day] || 0) + 1;
    result.byDate[dateStr] = (result.byDate[dateStr] || 0) + 1;
    result.byType[type] = (result.byType[type] || 0) + 1;
  });

  return result;
};

✅ 6. App.js 네비게이션 구조 예시

<Stack.Navigator initialRouteName="Login">
  <Stack.Screen name="Login" component={LoginScreen} options={{ title: '로그인' }} />
  <Stack.Screen name="AlarmDashboard" component={AlarmDashboardScreen} options={{ title: '내 알림 대시보드' }} />
</Stack.Navigator>

✅ 7. 실행 흐름 요약

  1. 앱 시작 → 로그인 화면 진입
  2. 로그인 성공 → Dashboard 화면으로 이동
  3. Victory 차트에 본인 알림 데이터만 필터링하여 출력
  4. 로그아웃 시 전체 초기화 가능 (선택 구현)

✅ 8. 추가 UX 기능 제안

기능 설명

로그아웃 버튼 auth().signOut() 추가 구현
가입 화면 (SignUpScreen) createUserWithEmailAndPassword() 활용 구현
비밀번호 재설정 sendPasswordResetEmail() 활용 가능

✅ 9. 이번 글에서 배운 것

  • Firebase Authentication을 이용한 사용자 로그인 구현
  • Firestore에 사용자 ID와 함께 알림 기록 저장
  • Victory 차트를 사용자별로 필터링하여 맞춤 통계 제공
  • 로그인 → 개인화 대시보드 UX 흐름 구성

📘 다음 확장 예고

✅ 관리자용 웹 대시보드와 연동 (Firebase Hosting + React)
✅ 사용자 유형/권한에 따라 알림 통계 분기
✅ 이메일 기반 사용자별 푸시 알림 타겟팅


 

React Native Firebase 로그인,React Native 사용자 인증,React Native 개인화 대시보드,React Native 알림 필터링,React Native Firestore 유저별 데이터,React Native 유저별 알림 관리,React Native Firebase Auth 예제,React Native 차트 필터링,React Native Push Notification 유저 분리,React Native 알림 UX 향상