Home > Software design >  react hooks changing state seems no change when calling from function to another
react hooks changing state seems no change when calling from function to another

Time:07-16

Here's what I have done so far:

Every time when changing checbox value either true/false it seems like the value from fetchAnswers function twisted from checkBoxAction function. Here's the original demo code in snack demo code. Notice that on console log that value from fetchAnswers oppose from the value coming from checkBoxAction

import React, {useContext, useEffect, useState} from "react";
import { Text, View, StyleSheet, CheckBox } from 'react-native';
import Constants from 'expo-constants';


import { Card } from 'react-native-paper';

export default function App() {
 const [showNew, setShowNew] = useState(true);

 const checkBoxAction =  async (status, checkBoxStatus) => {
    if(status === 'new') {
        console.log('checkBoxAction: ', checkBoxStatus)
        setShowNew(checkBoxStatus)
    }

    fetchAnswers()
 }

const fetchAnswers = async () => {
    console.log('fetchAnswers: ', showNew)
}

return (
 <View style={styles.container}>
    <CheckBox
        value={showNew}
        onChange={()=> checkBoxAction('new',(showNew?false:true))}
    />
  <Text style={styles.paragraph}>
    
  </Text>
</View>


 );
}

const styles = StyleSheet.create({
  container: {
  flex: 1,
  justifyContent: 'center',
  paddingTop: Constants.statusBarHeight,
  backgroundColor: '#ecf0f1',
  padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',


},



});

CodePudding user response:

setShowNew is setting the value after the whole function is done. That is why you see old values when you console log them. Either console.log checkBoxStatus since it is the newest value, or use an useEffect.

useEffect(()=> {
    console.log(showNew)
}, [showNew]) //Only run when showNew changes
  • Related