무작정 개인 프로젝트 해보기 - 6 (캘린더 연동하기, 로컬 스토리지로 전환하기)

오늘처음해요·2024년 3월 3일
0

작동 화면

관전 포인트 1. 캘린더의 날짜 별로 달라지는 투두리스트
관전 포인트 2. 앱을 재부팅해도 로컬 스토리지에 저장된 데이터가 로딩되는 것


캘린더 연동하기

react-native-calendar라는 라이브러리가 굉장히 세세하게 설정할 수 있게 되어있어서
그대로 사용했습니다

const TodoCalendar = () => {
  const [selectedDate, setSelectedDate] = useTodoListStore((state) => [
    state.selectedDate,
    state.setSelectedDate,
  ]);
  const [selected, setSelected] = useState(selectedDate);
  return (
    <CalendarView>
      <Calendar
        style={{}}
        theme={{
          textDayFontFamily: 'Lora',
          textMonthFontFamily: 'Lora',
          textDayHeaderFontFamily: 'Lora',
          textMonthFontSize: 20,
          backgroundColor: COLORS.bottomSheetBackGround,
          calendarBackground: COLORS.bottomSheetBackGround,
          todayTextColor: COLORS.pointColor,
          dayTextColor: COLORS.textWhite,
          monthTextColor: COLORS.textWhite,
          textDisabledColor: COLORS.grayText,
          selectedDayBackgroundColor: COLORS.textWhite,
          selectedDayTextColor: COLORS.mainBackGround,
          arrowColor: COLORS.textWhite,
          selectedDotColor: COLORS.mainBackGround,
        }}
        onDayPress={(day) => {
          setSelected(day.dateString);
          setSelectedDate(day.dateString);
        }}
        markedDates={{
          [selected]: {
            marked: true,
            selected: true,
            disableTouchEvent: false,
          },
        }}
        disableMonthChange={true}
        enableSwipeMonths={false}
        showSixWeeks={true}
      />
    </CalendarView>
  );

문제는 기존에 날짜를 고려하지 않고

todoList: [
  {
    id:0,
    title: '토익 단어 외우기'
    ...
  }
]

이렇게 전역변수로 관리하던 것을

todoList: {
	'2024-03-01' : [
      {
        id:0,
    	title: '토익 단어 외우기'
    	...
      },
      ...
    ]
}

이런 식으로 바꿔줘야 해서 좀 어려웠네요

add, update 등 todo를 수정하는 메서드도 날짜를 기준으로 수정하게끔 변경해줬습니다.


로컬 스토리지 이용하기

AsyncStorage 라이브러리를 통해 save, load를 구현해줬습니다

// store
import AsyncStorage from '@react-native-async-storage/async-storage';

const saveData = async (data) => {
  try {
    const jsonValue = JSON.stringify(data);
    await AsyncStorage.setItem('@todoList', jsonValue);
  } catch (e) {
    console.error(e);
  }
};
// App.js

const loadData = async () => {
  try {
    const jsonValue = await AsyncStorage.getItem('@todoList');
    console.log(`loadData : ${jsonValue}`);
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch (e) {
    console.error(e);
    return null;
  }
};

const initializeStore = async () => {
  const savedData = await loadData();
  if (savedData) {
    useTodoListStore.setState({ ...savedData });
  }
};

export default function App() {
 const [dataLoaded, setDataLoaded] = useState(false);

  useEffect(() => {
    async function loadFontsAsync() {
      await Font.loadAsync({
        Pretendard: require('@fonts/Pretendard-Regular.ttf'),
        Lora: require('@fonts/Lora-VariableFont_wght.ttf'),
      });
      setDataLoaded(true);
    }

    loadFontsAsync();
    initializeStore();
  }, []);

  if (!dataLoaded) {
    return <Loading />;
  }
} 

이런 식으로 렌더링 되기 전에 폰트와 로컬 스토리지에 저장된 값을 불러오게끔 했습니다

0개의 댓글