Issue
I suspect navigation.dispatch(CommonActions.reset())
is reseting the state before they can be passed as params.
Here is my setup:
I have defined a state variable like:
const [quizID, setQuizID] = useState<string>("");
And I have a button that resets the navigation stack like:
<Button onPress={() => {
console.log(quizID)
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: [
{ name: 'HomeScreenWithDrawer' },
{
name: 'Quiz',
params: {quizID: quizID},
}],
})
);
}}/>
This outputs to the console <empty string>
. It seems that quizID is getting reset just from including the dispatch code, like it is being reset before the dispatch is called, meaning the quizID cannot be passed as a parameter.
I tested it by only changing the code by removing the reset/dispatch part like:
<Button onPress={() => {
console.log(quizID)
}}/>
And it outputs the correct quizID.
So why is this happening, and how can I pass state variable as param for route specified in CommonActions.reset()?
Solution
Posting answer in case problem/solution generalizes past specific usage here and might help others (since reason is still unknown to me).
This way of passing a state variable into a reset route param should work without issues (tested and confirmed).
The problem was something to do with ProgressSteps from @joaosousa/react-native-progress-steps
package. I had my dispatch code nested within one of the steps, which doesn't work for some unknown reason.
As a workaround, set an effect hook on some state variable like:
const [viewQuiz, setViewQuiz] = useState(false);
useEffect(() => {
if(viewQuiz)
{
navigation.dispatch( (state: any) => {
return CommonActions.reset({
index: 1,
routes: [
{ name: 'HomeScreenWithDrawer' },
{
name: 'Quiz',
params: {quizID: quizID},
},
],
})
}
);
}
}, [viewQuiz]);
And within the step component, call setViewQuiz(true);
Answered By - Buretto
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.