0

in my code i used one context for saving data and one state for get active id . my problem is when i setState and then setContext , when i get state value i see state set default value !


export default function AddKnowledgeScreen({ route, navigation }) {

  const { TmpKnowledge, SetTmpKnowledge } = useContext(addKnowledgeContext);

   const [activeKnowlegeId, SetactiveKnowlegeId] = useState(-1);

  const myref = useRef(null);

return(
     <View style={{ flex: 1, alignItems: 'center', backgroundColor: Color.Background, }}>
          <Button
                onPress={() => {
                         SetactiveKnowlegeId(5);
                         var knowledgeData = { Id: 5, Name: "jack" };
                         SetTmpKnowledge(knowledgeData);
                        }>
          </Button>
     </View>
);
}

i found that when i set my context Screen reRendered and all state set with default values !

Meisan Saba
  • 800
  • 2
  • 9
  • 25

1 Answers1

0

Not sure if I got your question correctly,but I understand that you are trying to set your local state and right away use this new value to set your value in your context

If so, this would be because useState hook is asynchronous hence you still get the default value when setting your context value

Here are some links with more explanation in detail:

Why is setState in reactjs Async instead of Sync?

Is useState synchronous?

Elihu Del Valle
  • 337
  • 1
  • 3
  • 16