본문 바로가기
사지방앱개발

구름ide로 사지방에서 앱개발 3. Agenda 구현

by 오늘의코더 2022. 8. 15.
반응형

오늘 드디어 react-native-calendars의 Agenda 부분을 구현을 하였다. 일단 문서를 보면서 혼자서 구현해보려고 하였는데 도저히 모르겠어서 영어로 된 유튜브 강의를 보면서 따라서 만들었다.

Agenda

 

function MainScreen({ navigation, route }) {
	const { startDay, finishDay, time, cycle } = route.params;
	console.warn(typeof(startDay), finishDay);
	const [items, setItems] = useState({
		'2022-08-15': [
			{name: 'test 1', cookies: true},
			{name: 'test 2', cookies: true},
			{name: 'test 3', cookies: true},
		],
		'2022-08-16': [{name: 'test 2', cookies: false}],
	});
	
	// useEffect(() => {
	// 	const getData = async () => {
	// 		const response = await fetch(
	// 			'https://jsonplaceholder.typicode.com/posts'
	// 		);
	// 		const data = await response.json();
			
	// 		const mappedData = data.map((post, index) => {
				
	// 			const date = addDays(new Date(), index);
	// 			return {
	// 				...post,
	// 				date: format(date, 'yyyy-MM-dd'),
	// 			}
	// 		});
			
	// 		const reduced = mappedData.reduce((acc, currentItem) => {
	// 			const { date, ...coolItem } = currentItem;
				
	// 			acc[date] = [coolItem];
				
	// 			return acc;
	// 		}, {});
			
	// 		setItems(reduced); 
	// 	};
		
	// 	getData();
	// }, []);
	
	const renderItem = (item) => {
		return (
			<View style={styles.itemContainer}>
				<Text>{item.name}</Text>
				<Text>{item.cookies ? '🍪' : '22:00'}</Text>
			</View>
		)
	}
	
    return (
		<SafeAreaView style={styles.safe}>
			<Agenda 
				items={items} 
				renderItem={renderItem}
				/>
		</SafeAreaView>
	);
}

export default MainScreen;

const styles = StyleSheet.create({
  safe: {
	flex: 1,  
  },
  itemContainer: {
	backGroundColor: 'white',
	margin: 5,
	borderRadius: 15,
	justifyContent: 'center',
	alignItems: 'center',
  },
})

이부분이 강의 하신 최신버전인데 코드가 직관적이어서 이해하기가 쉽다. useEffect로 더미데이터를 만들어서 테스트 해봤는데 잘 작동한다.

const timeToString = (time) => {
    const date = new Date(time);
    return date.toISOString().split('T')[0];
};

function MainScreen({ navigation, route }) {
	const { startDay, finishDay, time, cycle } = route.params;
	console.warn(typeof(startDay), finishDay);
	const [items, setItems] = useState({});
	
	// useEffect(() => {
	// 	const getData = async () => {
	// 		const response = await fetch(
	// 			'https://jsonplaceholder.typicode.com/posts'
	// 		);
	// 		const data = await response.json();
			
	// 		const mappedData = data.map((post, index) => {
				
	// 			const date = addDays(new Date(), index);
	// 			return {
	// 				...post,
	// 				date: format(date, 'yyyy-MM-dd'),
	// 			}
	// 		});
			
	// 		const reduced = mappedData.reduce((acc, currentItem) => {
	// 			const { date, ...coolItem } = currentItem;
				
	// 			acc[date] = [coolItem];
				
	// 			return acc;
	// 		}, {});
			
	// 		setItems(reduced); 
	// 	};
		
	// 	getData();
	// }, []);
	
	const renderItem = (item) => {
		return (
			<View style={styles.itemContainer}>
				<Text>{item.name}</Text>
				<Text>{item.cookies ? '🍪' : '22:00'}</Text>
			</View>
		)
	}
	
	const loadItems = (day) => {
		const items = items || {};
		setTimeout(() => {
			for (let i = -15; i < 85; i++) {
				const time = day.timestamp + i * 24 * 60 * 60 * 1000;
				const strTime = timeToString(time);

				if (!items[strTime]) {
					items[strTime] = [];

					const numItems = Math.floor(Math.random() * 3 + 1);
					for (let j = 0; j < numItems; j++) {
						items[strTime].push({
						  name: 'Item for ' + strTime + ' #' + j,
						  height: Math.max(50, Math.floor(Math.random() * 150)),
						  day: strTime
						});
					}
				}
			}
			const newItems = {};
			Object.keys(items).forEach((key) => {
				newItems[key] = items[key];
			});
			setItems(newItems);
    	}, 1000)
	}
    return (
		<SafeAreaView style={styles.safe}>
			<Agenda
        		items={items}
        		loadItemsForMonth={loadItems}
        		selected={'2017-05-16'}
			/>
		</SafeAreaView>
	);
}

export default MainScreen;

이 코드는 옛날버전인데 Agenda공식 문서에는 지금도 이렇게 되어있다. 하지만 이해하기 어려워서 첫번째 방식으로 가기로 했다.

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }

비구조화 할당에 대해서도 자세히 알게 되었는데 ...rest이 부분을 이해해야 Agenda에서 더미데이터 생성부분을 이해 할 수 있었다.

이렇게 Agenda의 작동 원리는 이해할 수 있게 되었고 다음으로 Agenda에 들어갈 데이터를 만들어주는 것이 중요한데, 이 부분은 아직 어떻게 구현할지 고민해보고 있다. 생각해 보니까 시간을 그냥 TextInput으로 받는 게 좀 밋밋한 것 같아서 이 부분도 좀 더 보강해 보려고 한다. 근무를 다 마치면 체크박스를 눌러서 완료되었다고 표시하는 부분도 todo-list를 참고해서 한번 구현해 볼 것이다.

반응형

댓글