I'm new to Redux and redux toolkit. I'm making todo app to learn it. In there I can add and remove todos. Now I'm trying to edit it. However I don't see how I can send both the payload of the text I'm adding to my textinput (the one that is the "new" todo) AND the key so I know which one I pressed. Maybe I'm missing something simple or is there something I need to learn that I've misunderstood? Hope my code is not to messy to understand, thanks.
THIS IS MY SLICE:
export const todoSlice = createSlice({
name: "todo",
initialState:{todos:[{text:"test1", key:1}, {text:"test2", key:2}, {text:"test3", key:3}]},
reducers: {
addTodo: (state, action) => {
const todo = {key: Math.random(), text: action.payload,};
state.todos.push(todo);
},
removeTodo: (state, action) => {
state.todos = state.todos.filter((todo) => todo.key !== action.payload);
},
clearAll: (state) => {
state.todos = []
},
editTodo:(state, action) => {
//This is where I want to update the text
}
},
});
THIS IS THE APP:
export default function Home() {
const [text, setText] = useState("")
const [showModal, setShowModal] = useState(false)
const [modalText, setModalText] = useState()
const [newText, setNewText] = useState("")
const [currentItem, setCurrentItem] = useState()
const todos = useSelector((state) => state.todo.todos);
const dispatch = useDispatch();
const handleOnChangeText = (val) => {
setText(val)
}
const handleAddTodo = () => {
if (text.length > 0){
dispatch(addTodo(text))
setText("")
} else {
console.log("error")
}
}
const handleRemoveTodo = (item) => {
dispatch(removeTodo(item.key))
}
const handleClearAll = () => {
dispatch(clearAll())
}
const handleOnEditPress = (item) => {
setModalText(item.text)
setShowModal(true)
setCurrentItem(item)
}
const handleEditTodoText = (val) => {
setNewText(val)
}
const handleOnSavePress = () => {
dispatch(editTodo(newText))
}
return (
<SafeAreaView style={styles.container}>
{ showModal ? <EditModule
onClosePress={()=>setShowModal(false)}
title={modalText}
placeholder={modalText}
onChangeText={(val)=>handleEditTodoText(val)}
onSavePress={()=>handleOnSavePress()}
/> : null}
<View style={styles.topSection}>
<Text>Add text</Text>
<TextInput
placeholder='Write here'
style={styles.textinput}
onChangeText={(val)=>handleOnChangeText(val)}
value={text}
onBlur={()=>handleAddTodo()}
/>
<Button
text={"Add"}
onPress={()=>handleAddTodo()}
/>
<Button
text={"Clear all"}
onPress={()=>handleClearAll()}
/>
</View>
<View style={styles.bottomSection}>
<FlatList
data={todos}
renderItem={ ({item}) => (
<ListItem
text={item.text}
onPress={()=>handleRemoveTodo(item)}
onEditPress={()=>handleOnEditPress(item)}
/>)}
/>
</View>
</SafeAreaView>
)
}
@Rashomon had the answer. "The payload of your action should be an object containing both key and text. For example: {key: 1, text: "edited todo"}."