Jack_loc
Jack_loc

Reputation: 45

setState is not working within componentDidMount()

I apologize for posting repeated question, but I wasn't able to get my code working after reading all previous answers.

In my code, I try to read the URL parameter with queryString and update state with it using setState(). All within componentDidMount() method.


import React, {Component} from 'react';
import ChartBox from "./chartBox";
import Header from "./header";
import Footer from "./footer";
import Greeting from "./greeting";
import Menu from "./menu";
import Navbar from "./navbar";
import queryString from "query-string";



class Body extends Component{
    constructor(props){
        super(props);
        this.state = {
            username:""
        };
    }


    componentDidMount(){
        let user = queryString.parse(this.props.location.search);
        this.setState({username: user});

        console.log(this.state.username);
        console.log(user.user);
    }

    render(){
        return(
       <div>
           <Header />
           <Navbar />
           <Greeting user = {this.state.username}/>
           <ChartBox user = {this.state.username}/>
           <Menu user = {this.state.username}/>
           <Footer />
       </div>
        )
    }
}

export default Body;

queryString works fine and gets the correct value to the user variable. this.setState({username: user}); does not update state - I don't understand why. {this.state.username} does not passundefined to child components even if I explicitly set the initial state to some value.

I've seen mention that it might be a scope issue, but on the other hand I see examples on the internet that are no different from mine. I'm totally confused now.

Any help is greatly appreciated.

Upvotes: 0

Views: 404

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9769

setState is asynchronous.

It means you can’t call setState on one line and assume state has changed on the next.

setState({ name: "Michael" });
console.log(this.state.name);  //it won't show current updated state

How you can check this?

setState({ name: "Michael" },()=>{
  console.log(this.state.name);
});

Here you can check you your state updated or not as a callback.

Demo https://codesandbox.io/s/asynchronous-fc9zx

Upvotes: 0

x00
x00

Reputation: 13833

setState() is not guaranteed to be synchronous. this.state.username will update some time after componentDidMount() returns

Upvotes: 1

Related Questions