Grandad36
Grandad36

Reputation: 83

How to change the state in class component?

I can't update the state value. And how to load the textfield with the current state value?

Please see below:

class Form extends React.Component{
constructor(props){
    super(props);

    this.state = {
      user: '',
      firstName: '',
      lastName: '',
      email: ''
    }
  }
 handleChange(field, e){            
    let fields = this.state.fields;
    fields[field] = e.target.value;        
    this.setState({fields});
  }

  componentDidMount() {

  axios.all([
      axios.get(config.getUser),
      axios.get(config.getFullName).catch(function() { return false})
    ])
    .then(axios.spread(function (user, fullName) {

      console.log("USER: ", this.state.user)
      console.log("FULLNAME: ", this.state.fullName)
      var number = user.data.number;
      var firstName = user.data.firstName;
      var lastName = user.data.lastName;

      if (number !== undefined) {

        this.setState({user: number})
        console.log("NUMBER: ", this.state.user) ==> doesn't print

      }
      if (fullName !== false || firstName !== undefined) {

        this.setState({firstName: firstName}); 
        console.log("GET firstName: ",  this.state.firstName);  ==> doesn't print
        this.setState({lastName: lastName});
        console.log("GET lastName: ",  this.state.lastName);
      }    
  }))
 }
 render() {
  console.log("STATE: ", this.state)
    return (
        <div>
        <form name="form" onSubmit= {this.formSubmit.bind(this)} style={{minWidth: '515px'}}> 
            <Header title="Request" />
            <Paper style={styles.paperRequestForm}>
                <Grid container>
                    <TextField
                        required
                        name="number"
                        type="text"
                        label="number"
                        margin="dense"
                        variant="outlined"
                        // InputProps={{
                        //readOnly: true,
                        // }}
                        style={{width:202.5}}
                        InputProps={{
                          autoComplete: 'off',
                          style: {
                            font: '14px arial,serif',
                            backgroundColor: "white"
                            }}}
                        InputLabelProps={{
                          style: {
                              font: '14px arial,serif',
                              backgroundColor: "white"
                              }}}
                        onChange={this.handleChange.bind(this, "number")}
                        value={this.state.user} ==> does not load data 
                    />
                </Grid>

......

This are the response:

USER: Object { number: "541" }

FULLNAME: Object {"firstName": "Dee", "lastName": "Williamson"}

STATE:
Object { user: "", firstName: "", lastName: "" } ===> The states don't change.

Upvotes: 0

Views: 90

Answers (3)

Sanat Gupta
Sanat Gupta

Reputation: 1154

Hi Please change your handleChange function and text field, I hope it's helpful. Thanks

handleChange = (e) => {            
        this.setState({
            [e.target.name]:e.target.value
        });
    }


<TextField
    required
    name="number"
    type="text"
    label="number"
    margin="dense"
    variant="outlined"
    // InputProps={{
    //readOnly: true,
    // }}
    style={{width:202.5}}
    InputProps={{
    autoComplete: 'off',
    style: {
        font: '14px arial,serif',
        backgroundColor: "white"
    }}}
InputLabelProps={{
    style: {
        font: '14px arial,serif',
        backgroundColor: "white"
        }}}
onChange={(e) => this.handleChange(e)}
value={this.state.user}
/>

Upvotes: 0

harisu
harisu

Reputation: 1416

The first problem is with your handleChange function its doing exactly a different thing from what you intern it to do.

it should instead be

handleChange = (e) => {            
    this.setState({
        [e.target.name]:e.target.value
    });
}

Secondly your componentDidMount() also seems to be accessing fields that don't exist. It should rather look like below if we are considering the response you provided.


  componentDidMount() {

  axios.all([
      axios.get(config.getUser),
      axios.get(config.getFullName).catch(function() { return false})
    ])
    .then(axios.spread(function (user, fullName) {
      //here you should instead log the response(user and fullName) and not the states
      console.log("USER: ", user)
      console.log("FULLNAME: ", fullName)
      //basing on the format you provided on your post this is how you shoud extract them
      var number = user.number;
      var firstName = fullName.firstName;
      var lastName = fullName.lastName;

      if (number !== undefined) {

        this.setState({user: number}, console.log("NUMBER: ", this.state.user))


      }
      if (fullName !== false || firstName !== undefined) {
        //the printing is done in a callback to setState
        this.setState({firstName: firstName}, console.log("GET firstName: ",  this.state.firstName)); 
        ; 
        this.setState({lastName: lastName});

      }    
  }))
 }

Then finally your textfield should be as follows

                    <TextField
                        required
                        //note here the name is user and not number
                        name="user"
                        type="text"
                        label="number"
                        margin="dense"
                        variant="outlined"
                        // InputProps={{
                        //readOnly: true,
                        // }}
                        style={{width:202.5}}
                        InputProps={{
                          autoComplete: 'off',
                          style: {
                            font: '14px arial,serif',
                            backgroundColor: "white"
                            }}}
                        InputLabelProps={{
                          style: {
                              font: '14px arial,serif',
                              backgroundColor: "white"
                              }}}
                        //call the handleChange here
                        onChange={this.handleChange}
                        value={this.state.user}  
                    />

Upvotes: 1

Sivaprasad derangula
Sivaprasad derangula

Reputation: 1169

setState() is async, you can't get updated value in immediate line. you should use any other life cycle event (componentWillUpdate() or in render()) or you can pass a callback to setState() as below:

      if (number !== undefined) {

        this.setState({user: number}, ()=> console.log("NUMBER: ", this.state.user))
      }
      if (fullName !== false || firstName !== undefined) {

        this.setState({firstName: firstName}, ()=>console.log("GET firstName: ",  this.state.firstName); ); 
        this.setState({lastName: lastName}, ()=> console.log("GET lastName: ",  this.state.lastName));
        ;
      } 

Upvotes: 0

Related Questions