V
V
Vladimir2022-04-04 13:25:41
React
Vladimir, 2022-04-04 13:25:41

How to organize access to the state in this case (navigation.addListener())?

Help, please, I've already broken my head. There is a functional component, it has a state, and there is a need to catch the output from this component and save the state to a file. I do it like this:

React.useEffect(
    () =>
      navigation.addListener('beforeRemove', (e) => {
        // Prevent default behavior of leaving the screen
        e.preventDefault();
        // Prompt the user before leaving the screen
        Alert.alert(
          "Вы уверены?",
          "Вы точно хотите завершить?",
          [
            { text: "Нет, продолжаем", style: 'cancel', onPress: () => { } },
            {
              text: "Да, завершить",
              style: 'destructive',
              onPress: () => {
                writeData(logData)
                navigation.dispatch(e.data.action)
              },
            },
          ]
        );
      }),
    [navigation]
  );


State is actually logData. The problem is that I always see only the default state of the state. And even if I try to access it not from the event handler, but from writeData (this is a function declared inside the component), the same thing still happens. There is no way to get the actual value of the state.

It is clear that there is something simple here that I do not understand, tell me what?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Goretsky, 2022-04-04
@rqdkmndh

The state is set asynchronously. React guarantees a new state on a new render. The trouble for all beginners is that they throw a value into the state and expect to get it literally on the next line. And the react itself decides when to update this property, because updating the property is a new render. The class components had a callback function that was called immediately after updating the property in the state. In functional components, this callback was removed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question