sod.heretic
sod.heretic

Reputation: 126

cant show updated state (REACT-NATIVE)

I want to show updated state name in the sidedrawer of my app,my functions work fine as I can see the name PRINTED twice in the console but for some reason I cannot show the name value on the app screen(shows starting value ""),I am thinking i might be using the wrong lifecycle method can someone help me?

state = {
    name: {
        value: ""
    }

componentWillMount() {

getTokens((value) => {
        if (value[0][1] === null) {
            alert('whoops')
        } else {
            this.props.UpdateUserData(value[0][1]).then(()=>{
                console.log(this.props.User.userData)
            this.state.name.value = this.props.User.userData
            console.log(this.state.name.value)
            })
}
    })
}
 render() {
    return (

        <View style={styles.container}>
                <Text style={styles.displayname}>{this.state.name.value} 
                 </Text>
        </View>
    )
}

Upvotes: 0

Views: 408

Answers (4)

Snehassingh
Snehassingh

Reputation: 1

componentWillMount does not differ much from constructor - it is also called once only in the initial mounting life-cycle. Many will be tempted to use this function in order to send a request to fetch data and expect the data to be available before the initial render is ready. This is not the case — while the request will be initialized before the render, it will not be able to finish before the render is called.

this.setState can solve the issue in this case.

Upvotes: 0

Nirmal Dalmia
Nirmal Dalmia

Reputation: 327

You are using this.state.name.value which is not correct. It sets the state but doesn't actually cause the component to re-render itself. Instead, you need to use the setState method to change the value of a state. This will make a call to re-render the component after the state has been changed. The example of that approach would be

this.setState({ name: this.propos.User.userData });

Although this approach works but it's not advised to mutate the value of state. States need to be considered immutable according to the guidelines.

Upvotes: 0

Isaac
Isaac

Reputation: 12874

this.state.name.value = this.props.User.userData

Do not mutate your state directly because it won't rerender component, instead using setState method as below

this.setState({ name: this.props.User.userData });

Upvotes: 1

Alex Antonov
Alex Antonov

Reputation: 15146

A quote from react-bits

Avoid async initialization in componentWillMount()

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.

Replace componentWillMount with componentDidMount. Should work

Upvotes: 0

Related Questions