M
M
MrChen2017-08-16 17:02:23
JavaScript
MrChen, 2017-08-16 17:02:23

How to deal with setState in React?

Hello! Here is the code of my component (first you need to read it):

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

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

        this.state = {
            articles: {},

            messages: {
                error: '',
                success: false
            }
        };

        this.handleChangeForm = this.handleChangeForm.bind(this);
        this.handleSubmitForm = this.handleSubmitForm.bind(this);
    }

    handleChangeForm(event) {
        let name = event.target.name;
        let articles = Object.assign({}, this.state.articles);
        articles[name] = event.target.value;
        this.setState({articles});
    }

    handleSubmitForm(event) {
        event.preventDefault();

        let message = Object.assign({}, this.state.messages);

        axios.post('/articles/add', {
            title: this.state.articles.title,
            content: this.state.articles.content
        })
            .then(function(response) {
                message.success = true;
            })
            .catch(function(error) {
                message.error = error;
            });

        this.setState({
            messages: message
        });
    }

    render() {
        return (
            <form onChange={this.handleChangeForm} onSubmit={this.handleSubmitForm}>
                {this.state.messages.success && (
                    <div>
                        Статья успешно добавлена
                    </div>
                )}

                {this.state.messages.error && (
                    <div>
                        Произошла ошибка при добавлении: {this.state.messages.error}
                    </div>
                )}

                <input type="text" placeholder="title" name="title"/> <br/>
                <input type="text" placeholder="content" name="content"/> <br/>

                <input type="submit" value="Добавить статью"/>
            </form>
        )
    }
}

ReactDOM.render(<Form />, document.getElementById('app'));

When I click the "Add Article" button, the message "Article added successfully" does not appear. It appears only when the value of one of the fields changes. How to deal with it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Minakov, 2017-08-16
@MrChen

In your code, setState twitches before the promise is resolved/rejected. Accordingly, the old state is still in the message object at the time setState is called. Fix like this:

handleSubmitForm(event) {
  event.preventDefault();

  let message = Object.assign({}, this.state.messages);

  axios.post('/articles/add', {
    title: this.state.articles.title,
    content: this.state.articles.content
  })
    .then(function(response) {
      message.success = true;

      this.setState({
        messages: message
      });
    })
    .catch(function(error) {
      message.error = error;

      this.setState({
        messages: message
      });
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question