Search code examples
reactjsreact-nativestatereact-state-management

React - State return undefined


I use state variable on my class but it seems doesn't work. And when i try to see its value via console.log it returns undefined. What am i doing wrong?

class ContactScreen extends Component {

    static contextType = Context

    constructor(props) {
        super(props)
        this.state = {
            searchMode: false //this is my variable
        }
        setTimeout(() => {
          StatusBar.setBackgroundColor(primary)
        }, 100)
    }

    onContactAction = (contact) =>  {
        this.props.navigation.navigate('Chat', {contact})
    }

    render() {
        const { state } = this.context
        const { contactList } = state

        return (
            <Container>
                { this.searchMode ? //validate variable value
                    <SearchHeader/> :
                    <Header style= {appStyles.headerBackgroundColor}>
                        ...
                        <Right>
                            <Button 
                                transparent 
                                style={{marginRight:5}}
                                onPress={() => {
                                    this.setState({searchMode: true}) //set variable value
                                    console.log(this.searchMode)
                                }}>
                                <Icon type= 'Octicons' name= 'search'/>
                            </Button>
                            <PopupMenu type= 'main'/>
                        </Right>
                    </Header>
                }    
                <ContactList onContactAction={(id) => this.onContactAction(id)}/>
            </Container>
        )
    }
}

Solution

  • There are two issues:

    You are missing 'state' in your console.log.

    console.log(this.state.searchMode)
    

    However, if we log it now you will get a stale value of this.state.searchMode. This is because setState is asynchronous. However, setState accepts a callback in the second parameter that will be called after the setState is complete so you can log the new state. Update your onPress to this:

    onPress={() => {
      this.setState({searchMode: true}, () => console.log(this.state.searchMode))
    }}