Solution
First, we'll need to move the moodList
and the handleSelectMood
to the App.provider.tsx
and expose them from context instead.
src/App.provider.tsx
import React from 'react';+import { MoodOptionType, MoodOptionWithTimestamp } from './types'; type AppContextType = {- greeting: string;+ moodList: MoodOptionWithTimestamp[];+ handleSelectMood: (mood: MoodOptionType) => void; }; const defaultValue = {- greeting: '',+ moodList: [],+ handleSelectMood: () => {}, }; const AppContext = React.createContext<AppContextType>(defaultValue); export const AppProvider: React.FC = ({ children }) => {+ const [moodList, setMoodList] = React.useState<MoodOptionWithTimestamp[]>([]);++ const handleSelectMood = React.useCallback((mood: MoodOptionType) => {+ setMoodList(current => [...current, { mood, timestamp: Date.now() }]);+ }, []);+ return (- <AppContext.Provider value={{ greeting: 'Hello' }}>+ <AppContext.Provider value={{ moodList, handleSelectMood }}> {children} </AppContext.Provider> );
Next, we can remove them from Home.screen.tsx
and read them from context:
src/screens/Home.screen.tsx
import React from 'react'; import { StyleSheet, View } from 'react-native';-import { MoodItemRow } from '../components/MoodItemRow';+import { useAppContext } from '../App.provider'; import { MoodPicker } from '../components/MoodPicker';-import { MoodOptionType, MoodOptionWithTimestamp } from '../types'; export const Home: React.FC = () => {- const [moodList, setMoodList] = React.useState<MoodOptionWithTimestamp[]>([]);-- const handleSelectMood = React.useCallback((mood: MoodOptionType) => {- setMoodList(current => [...current, { mood, timestamp: Date.now() }]);- }, []);+ const appContext = useAppContext(); return ( <View style={styles.container}>- <MoodPicker onSelect={handleSelectMood} />- {moodList.map(item => (- <MoodItemRow item={item} key={item.timestamp} />- ))}+ <MoodPicker onSelect={appContext.handleSelectMood} /> </View> ); };
And finally we can display the past moods from the History tab:
src/screens/History.screen.tsx
import React from 'react';-import { StyleSheet, View, Text } from 'react-native';+import { ScrollView } from 'react-native'; import { useAppContext } from '../App.provider';+import { MoodItemRow } from '../components/MoodItemRow';
export const History: React.FC = () => { const appContext = useAppContext(); return (- <View style={styles.container}>- <Text>History</Text>- <Text>{appContext.greeting}</Text>- </View>+ <ScrollView>+ {appContext.moodList.map(item => (+ <MoodItemRow item={item} key={item.timestamp} />+ ))}+ </ScrollView> ); };--const styles = StyleSheet.create({- container: {- flex: 1,- },-});