I've made a simple todo/goals application as a learning project where I use context for state management.
So in the app I create a goal item with unique ID but then I want to be able to enter that specific item when I press the "gear" symbol from the Home screen. (In here I will add ways to edit the text and delete the item later.)
I'm new to context so I get confused when I try to figure out how to pass the information of the item. Please can someone help me, here's the code:
Home.js
export default Home = ({navigation, item}) => {
const {goals} = useContext(GoalsListContext)
const handleSettingPress = () => {
navigation.navigate("EditGoal")
}
return(
<View style={styles.container}>
<Button title="Create new goal!" onPress={()=>navigation.navigate("AddGoal")}/>
{goals.length ? (
<FlatList
data={goals}
keyExtractor={(goal)=>goal.id}
renderItem={({item})=> {
return <View style={styles.goalContainer}><Text style={styles.goalContainerText}>{item.text}</Text><TouchableOpacity onPress={handleSettingPress}><FontAwesome name="gear" size={30} color="white" /></TouchableOpacity></View>
}}
/>)
: (<Text>You have no todos</Text>)}
</View>
editGoal.js
export default EditGoal = () => {
return(
<View style={styles.container}>
***This is where I want to be able to edit and delete the goal***
</View>
)
}
addGoal.js
export default AddGoal = ({navigation, route}) => {
const {goals, addGoal} = useContext(GoalsListContext)
const [goal, setGoal] = useState('')
const handleChange = (text) => {
setGoal(text)
}
const handleAddGoal = () => {
addGoal(goal)
setGoal('')
navigation.goBack()
}
return(
<View style={styles.container}>
<Text>Add your goal</Text>
<TextInput
placeholder="Name of goal"
style={styles.input}
value={goal}
onChangeText={(text)=>handleChange(text)}
/>
<Button
title="Create goal"
onPress={handleAddGoal}
/>
</View>
)
}
My context file:
const GoalsListContextProvider = ({children}) => {
const [goals, setGoals] = useState([{text: 'Clean the house', id:'1'}])
const addGoal = (goal) => {
setGoals([...goals, {text: goal, id:`${Math.random()}`}])
}
return(
<GoalsListContext.Provider value={{goals, addGoal}}>
{children}
</GoalsListContext.Provider>
)
}