스파르타코딩클럽 4주차_[숙제]

toto9602·2021년 11월 7일
0

React-Native 스터디

목록 보기
7/7

<스파르타코딩클럽 4주차 숙제>

LikePage.js

#기억해 둘 내용#

1. LogBox.ignoreAllLogs()
-> console.disableYellowBox() 대신 사용한다.
2. Alert.alert()
-> 첫 번째 인자로 팝업창 title을,
두 번째 인자로 팝업창 내용을,
세 번째 인자로 팝업창 버튼의 텍스트와,
버튼을 눌렀을 때 실행할 함수를 입력받을 수 있다.
3. tip의 데이터 구조는 다시 봐야 할 것 같다.

import React, { useState, useEffect } from 'react';
import main from '../assets/main.png';
import { StyleSheet, Text, View, Image, TouchableOpacity, ScrollView, Alert } from 'react-native';
import data from '../data.json';
import LikeCard from '../components/LikeCard';
import Loading from '../components/Loading';
import { StatusBar } from 'expo-status-bar';
import { firebase_db } from "../firebaseConfig"
import Constants from 'expo-constants';
import { LogBox } from 'react-native';
export default function LikePage({ navigation, route }) {
    LogBox.ignoreAllLogs();
    const [tip, setTip] = useState([])

    const [ready, setReady] = useState(true)

    useEffect(() => {
        setTimeout(() => {
            navigation.setOptions({
                title: '꿀팁 찜'
            })
            const user_id = Constants.installationId;
            firebase_db.ref(`/like/${user_id}`).once('value').then((snapshot) => { // 데이터를 가져와서 (숙제 1)
                let tip = snapshot.val();
                console.log(tip); //데이터가 null인지 확인
                if (tip === null) { //데이터가 없으면, alert -> 확인 누르면 MainPage로 페이지 이동 (숙제 2) == LikePage에서 데이터 다 삭제했을 때도 alert 작동하게
                    Alert.alert('<찜 목록 없음>', '찜한 꿀팁이 없습니다!', [{text: '확인', onPress:()=>{navigation.navigate('MainPage')}}])
                }
                else { //데이터가 있으면, setTip해서 데이터를 보여준다.  (숙제 1)
                    setTip(Object.values(tip))
                    setReady(false)
                }
                console.log(tip.length);
                console.log(ready);
            })
        }, 300);
    })

    return ready ? <Loading /> : (
        <ScrollView style={styles.container}>
            {
                tip.map((content, i) => {
                    return (<LikeCard key={i} content={content} navigation={navigation} />)
                }
                )
            }
        </ScrollView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    }
})

LikeCard.js

import React from 'react';
import { View, Image, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native'
import { firebase_db } from '../firebaseConfig';
import Constants from 'expo-constants';
//MainPage로 부터 navigation 속성을 전달받아 Card 컴포넌트 안에서 사용
export default function Card({ content, navigation }) {

    const remove = () => {
        const user_id = Constants.installationId;
        const data_remove = firebase_db.ref(`/like/${user_id}/${content.idx}`).remove().then(() => {
            Alert.alert('<찜 해제 완료>', '찜 해제가 완료되었습니다',
                [{ text: '확인', onPress: () => { navigation.navigate('LikePage') } }]);
        }).catch(() => {
            Alert.alert('삭제하기 실패!');

        }) //데이터 삭제하면, <찜 해제 완료> 팝업 -> 확인 누르면 LikePage로 navigate / 실패하면 팝업 표시
    }

    return (
        //카드 자체가 버튼역할로써 누르게되면 상세페이지로 넘어가게끔 TouchableOpacity를 사용
        <View style={styles.card} onPress={() => { navigation.navigate('DetailPage', content) }}>
            <Image style={styles.cardImage} source={{ uri: content.image }} />
            <View style={styles.cardText}>
                <Text style={styles.cardTitle} numberOfLines={1}>{content.title}</Text>
                <Text style={styles.cardDesc} numberOfLines={3}>{content.desc}</Text>
                <Text style={styles.cardDate}>{content.date}</Text>
                <View style={styles.button_box}> 
                    <TouchableOpacity style={styles.button} onPress={() => { navigation.navigate('DetailPage', { idx: content.idx }) }}> 
                        <Text style={styles.button_text}>자세히보기</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button} onPress={() => remove()}>
                        <Text style={styles.button_text}>찜 해제</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View> //숙제 3,4,5
    )
}

styleSheet 생략

profile
주니어 백엔드 개발자입니다! 조용한 시간에 읽고 쓰는 것을 좋아합니다 :)

0개의 댓글