Skip to content

Commit

Permalink
Fix/heart store
Browse files Browse the repository at this point in the history
  • Loading branch information
sjsjmine129 committed May 27, 2024
1 parent 3734466 commit 940d93e
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 74 deletions.
41 changes: 17 additions & 24 deletions src/components/MyStore.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
import React, { useContext, useRef } from 'react';
import {
View,
Text,
ScrollView,
StyleSheet,
Image,
} from 'react-native';
import {
COLOR_WHITE,
COLOR_TEXT70GRAY,
} from '../assets/color';
import { useNavigation } from '@react-navigation/native';
import React, {useContext, useRef} from 'react';
import {View, Text, ScrollView, StyleSheet, Image} from 'react-native';
import {COLOR_WHITE, COLOR_TEXT70GRAY} from '../assets/color';
import {useNavigation} from '@react-navigation/native';
import AppContext from './AppContext';
import { Dimensions } from 'react-native';
import {Dimensions} from 'react-native';
import AnimatedButton from './AnimationButton';

const windowWidth = Dimensions.get('window').width;
Expand All @@ -23,11 +14,12 @@ export default function MyStore(props) {

const scrollViewRef = useRef();

const { passData, onEndReached, hasMore } = props;
const {passData, onEndReached, hasMore} = props;

const handleScroll = (event) => {
const { contentOffset, layoutMeasurement, contentSize } = event.nativeEvent;
const isCloseToEnd = contentOffset.x + layoutMeasurement.width >= contentSize.width - 50;
const handleScroll = event => {
const {contentOffset, layoutMeasurement, contentSize} = event.nativeEvent;
const isCloseToEnd =
contentOffset.x + layoutMeasurement.width >= contentSize.width - 50;

if (isCloseToEnd && hasMore) {
onEndReached();
Expand All @@ -47,17 +39,17 @@ export default function MyStore(props) {
horizontal={true}
ref={scrollViewRef}
onScroll={handleScroll}
scrollEventThrottle={16}
>
<View style={{ width: 16 }} />
scrollEventThrottle={16}>
{/* <View style={{width: 16}} /> */}
{passData.map((data, index) => {
return (
<AnimatedButton
key={index.toString()}
style={styles.kingopassKard}
onPress={() => {
console.log('찜한 가게 페이지로 이동');
navigation.navigate('StoreDetail', { data: data });
//TODO: 찜한 가게 불러올 때 가게 id가 안나옴
console.log('찜한 가게 페이지로 이동', data);
navigation.navigate('StoreDetail', {data: data});
}}>
<Image
source={{
Expand Down Expand Up @@ -101,7 +93,7 @@ export default function MyStore(props) {
</AnimatedButton>
);
})}
<View style={{ width: 16 }} />
{/* <View style={{width: 16}} /> */}
</ScrollView>
)}
</View>
Expand All @@ -119,6 +111,7 @@ const styles = StyleSheet.create({
marginLeft: 26,
color: COLOR_TEXT70GRAY,
fontWeight: '700',
marginBottom: 10,
},
kingopassKard: {
height: 140,
Expand Down
27 changes: 19 additions & 8 deletions src/screens/mypage/MypageScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import MyStore from '../../components/MyStore';
import axios from 'axios';
import AppContext from '../../components/AppContext';
import {API_URL} from '@env';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function MyPageScreen() {
const navigation = useNavigation();
Expand All @@ -33,8 +34,10 @@ export default function MyPageScreen() {

const fetchUserInfo = async () => {
try {
console.log('User ID:', context.id);
const response = await axios.get(`${API_URL}/v1/users/${context.id}`, {
const userId = await AsyncStorage.getItem('userId');
console.log('User ID:', userId);

const response = await axios.get(`${API_URL}/v1/users/${userId}`, {
headers: {Authorization: `Bearer ${context.accessToken}`},
});
console.log('User Info:', response.data);
Expand Down Expand Up @@ -80,17 +83,21 @@ export default function MyPageScreen() {
const fetchLikedStores = async page => {
try {
const response = await axios.get(
`${API_URL}/v1/restaurants/my-like?page=${page}&size=5`,
`${API_URL}/v1/restaurants/my-like?page=${page}&size=20`,
{
headers: {Authorization: `Bearer ${context.accessToken}`},
},
);

console.log('Liked Stores Response:', response.data);
console.log(
'Liked Stores Response:',
response.data.data.restaurants.content,
);

const stores = response.data.data.restaurants.content.map(store => ({
name: store.name,
image: store.representativeImageUrl,
id: store.id,
}));

setMyStoresData(prevStores => [...prevStores, ...stores]);
Expand All @@ -105,18 +112,20 @@ export default function MyPageScreen() {
fetchUserInfo();
setReviewPage(0);
setStorePage(0);
setMyReviews([]);
setMyStoresData([]);
// setMyReviews([]);
// setMyStoresData([]);
// fetchMyReviews(0);
// fetchLikedStores(0);
}, []),
);

useEffect(() => {
fetchMyReviews(reviewPage);
}, [context.accessToken, context.id, reviewPage]);
}, [context.accessToken, reviewPage]);

useEffect(() => {
fetchLikedStores(storePage);
}, [context.accessToken, context.id, storePage]);
}, [context.accessToken, storePage]);

const handleLoadMoreReviews = () => {
if (hasMoreReviews) {
Expand Down Expand Up @@ -155,6 +164,7 @@ export default function MyPageScreen() {
source={require('../../assets/right-arrow.png')}
/>
</TouchableOpacity>

<MyStore
passData={myStoresData}
onEndReached={handleLoadMoreStores}
Expand All @@ -179,6 +189,7 @@ const styles = StyleSheet.create({
entire: {
backgroundColor: COLOR_BACKGROUND,
alignItems: 'center',
flex: 1,
},
myPageItem: {
width: 100,
Expand Down
105 changes: 63 additions & 42 deletions src/screens/mypage/UserDataChangeScreen.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import React, { useState, useContext, useEffect } from 'react';
import { View, ScrollView, StyleSheet, Image, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import React, {useState, useContext, useEffect} from 'react';
import {
View,
ScrollView,
StyleSheet,
Image,
Text,
TextInput,
TouchableOpacity,
Alert,
} from 'react-native';
import {
COLOR_BACKGROUND,
COLOR_PRIMARY,
Expand All @@ -9,12 +18,12 @@ import {
COLOR_RED,
COLOR_BLUE,
} from '../../assets/color';
import { useNavigation, CommonActions } from '@react-navigation/native';
import {useNavigation, CommonActions} from '@react-navigation/native';
import Header from '../../components/Header';
import AsyncStorage from '@react-native-async-storage/async-storage';
import AppContext from '../../components/AppContext';
import axios from 'axios';
import { API_URL } from '@env';
import {API_URL} from '@env';

export default function UserDataChangeScreen() {
const navigation = useNavigation();
Expand All @@ -28,73 +37,81 @@ export default function UserDataChangeScreen() {
useEffect(() => {
const fetchUserInfo = async () => {
try {
console.log(`Fetching user info with userId: ${context.id}`);
const userId = await AsyncStorage.getItem('userId');

console.log(`Fetching user info with userId: ${userId}`);
console.log(`Using accessToken: ${context.accessToken}`);
const response = await axios.get(
`${API_URL}/v1/users/${context.id}`,
{
headers: { Authorization: `Bearer ${context.accessToken}` },
}
);
const response = await axios.get(`${API_URL}/v1/users/${userId}`, {
headers: {Authorization: `Bearer ${context.accessToken}`},
});

console.log('User Info API Response:', response.data);
setNickname(response.data.data.userDto.nickname);
setEmail(response.data.data.userDto.email);
} catch (error) {
console.error("Failed to fetch user info:", error);
console.error('Failed to fetch user info:', error);
}
};

fetchUserInfo();
}, [context.accessToken, context.id]);
}, [context.accessToken]);

const nicknameCheckHandler = async () => {
try {
const response = await axios.get(`${API_URL}/v1/users/check-nickname`, {
params: { nickname },
headers: { Authorization: `Bearer ${context.accessToken}` }
params: {nickname},
headers: {Authorization: `Bearer ${context.accessToken}`},
});

if (response.data.isDuplicate || nickname === context.nickname) {
setDuplicateMessage("이미 사용 중인 닉네임입니다.");
setDuplicateMessage('이미 사용 중인 닉네임입니다.');
setMessageColor(COLOR_RED);
} else {
setDuplicateMessage("사용 가능한 닉네임입니다.");
setDuplicateMessage('사용 가능한 닉네임입니다.');
setMessageColor(COLOR_BLUE);
}
} catch (error) {
setDuplicateMessage("이미 사용 중인 닉네임입니다.");
setDuplicateMessage('이미 사용 중인 닉네임입니다.');
setMessageColor(COLOR_RED);
}
};

const updateNicknameHandler = async () => {
try {
const response = await axios.patch(`${API_URL}/v1/users`, {
nickname: nickname
}, {
headers: { Authorization: `Bearer ${context.accessToken}` }
});
const response = await axios.patch(
`${API_URL}/v1/users`,
{
nickname: nickname,
},
{
headers: {Authorization: `Bearer ${context.accessToken}`},
},
);

if (response.status === 200) {
Alert.alert("성공", "닉네임이 성공적으로 변경되었습니다.", [{ text: "확인", onPress: () => navigation.goBack() }]);
Alert.alert('성공', '닉네임이 성공적으로 변경되었습니다.', [
{text: '확인', onPress: () => navigation.goBack()},
]);
}
} catch (error) {
console.error("Failed to update nickname:", error);
Alert.alert("오류", "닉네임 변경 중 오류가 발생했습니다.", [{ text: "확인" }]);
console.error('Failed to update nickname:', error);
Alert.alert('오류', '닉네임 변경 중 오류가 발생했습니다.', [
{text: '확인'},
]);
}
};

const deleteUserHandler = async () => {
try {
const response = await axios.delete(`${API_URL}/v1/users`, {
headers: { Authorization: `Bearer ${context.accessToken}` }
headers: {Authorization: `Bearer ${context.accessToken}`},
});

if (response.status === 200) {
Alert.alert("성공", "회원탈퇴가 정상적으로 완료되었습니다.", [
Alert.alert('성공', '회원탈퇴가 정상적으로 완료되었습니다.', [
{
text: "확인", onPress: async () => {
text: '확인',
onPress: async () => {
await AsyncStorage.removeItem('accessToken');
await AsyncStorage.removeItem('refreshToken');
context.setAccessTokenValue(null);
Expand All @@ -103,16 +120,16 @@ export default function UserDataChangeScreen() {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: 'Splash' }],
})
routes: [{name: 'Splash'}],
}),
);
}
}
},
},
]);
}
} catch (error) {
console.error("Failed to delete user:", error);
Alert.alert("오류", "회원탈퇴 중 오류가 발생했습니다.", [{ text: "확인" }]);
console.error('Failed to delete user:', error);
Alert.alert('오류', '회원탈퇴 중 오류가 발생했습니다.', [{text: '확인'}]);
}
};

Expand All @@ -127,8 +144,8 @@ export default function UserDataChangeScreen() {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: 'Splash' }],
})
routes: [{name: 'Splash'}],
}),
);
} catch (error) {
console.log('Error during logout:', error);
Expand All @@ -142,24 +159,26 @@ export default function UserDataChangeScreen() {
<Image
style={[styles.myPageItem, styles.myPageItemLayout]}
resizeMode="cover"
source={require("../../assets/skku.png")}
source={require('../../assets/skku.png')}
/>

<View style={styles.inputContainer}>
<Text style={styles.label}>닉네임</Text>
<View style={styles.inputWithButton}>
<TextInput
style={[styles.input, { flex: 1 }]}
style={[styles.input, {flex: 1}]}
value={nickname}
onChangeText={setNickname}
placeholder="닉네임을 입력해주세요"
/>
<TouchableOpacity style={styles.checkButton} onPress={nicknameCheckHandler}>
<TouchableOpacity
style={styles.checkButton}
onPress={nicknameCheckHandler}>
<Text style={styles.checkButtonText}>중복확인</Text>
</TouchableOpacity>
</View>
{duplicateMessage ? (
<Text style={[styles.duplicateMessage, { color: messageColor }]}>
<Text style={[styles.duplicateMessage, {color: messageColor}]}>
{duplicateMessage}
</Text>
) : null}
Expand All @@ -174,7 +193,9 @@ export default function UserDataChangeScreen() {
/>
</View>

<TouchableOpacity style={styles.updateButton} onPress={updateNicknameHandler}>
<TouchableOpacity
style={styles.updateButton}
onPress={updateNicknameHandler}>
<Text style={styles.updateButtonText}>수정하기</Text>
</TouchableOpacity>

Expand Down

0 comments on commit 940d93e

Please sign in to comment.