Reputation: 530
I am trying to perform add function on my list. The way it works is that I have a parent screen showing the whole list of items with a button at the top (navigation bar) to add a new item. The problem is that if I add a new item (and it adds correctly to the list of items), the navigation function does not receive the right state of items when going to child screen again, causing a mismatch number of items upon the new task creation.
Parent.js
const handleOpenNewTask = () => {
//items before going to child screen (onTaskCreated is a callback from child to update list)
//this is where the wrong number of items shows, taskList is not updated here!
console.log(taskList)
navigation.navigate(routes.NEW_TASK, {
onTaskCreated
});
};
//callback when child screen is finished
const onTaskCreated = ({ newTask, id }) => {
// Create a new array based on current state:
let list = [...taskList];
// Add item to it
list.push({value: id});
//updates correctly first time
setTaskList(list);
};
//update header with button to add new item
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<NewTaskHeaderRight onClick={() => handleOpenNewTask()} />
),
});
}, [navigation]);
Basically, if I have an empty list and go to child screen it would add it to the list and show on the screen. However, when I go to child screen again, the taskList
in handleOpenNewTask
is not updated and I assume I am doing it wrong because navigation doesn't catch the taskList
state? What should I do?
Upvotes: 0
Views: 25
Reputation: 16354
Try something like below, Pass the taskList as a dependency to the hook, which will cause the navigation to update with new state.
useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<NewTaskHeaderRight onClick={() => handleOpenNewTask()} />
),
});
}, [navigation,taskList]);
Upvotes: 1