Michael Du Michael Du - 2 months ago 8
React JSX Question

How to retrieve the entire state of a component as a single object?

I currently have my getInitialState set up such that the keys and values match up exactly for an AJAX POST call. The state gets completed as the form gets filled, and when the user clicks submit, I'd like for it to just grab the entire state, JSON.stringify it, and then make the post call with that data.

Is that possible? Or do I have to write out some code to map it all out in a new object? If so, what's the quickest way for that that?

Answer

If you do indeed have all your data serialized in your component's state, you don't need to do much to access it. It's available to any method via this.state. If you're using es6 classes it'd look something like:

class MyForm extends React.Component {
    constructor() {
        super();

        // in es6 Components you need to bind custom methods like this in order to get the this context when called
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit() {
        // assuming you've been collecting data in state as the user types you can just grab the state
        const data = JSON.stringify(this.state);

        // you'll need an ajax library or you can use fetch
        fetch(someurl, {
          method: 'POST',
          body: data,
        }).then(resp => {
          // handle response
        });
    }

    render() {
        return (
            <form onSubmit={this.onSubmit}>
              {/* your inputs here */}
            </form>
        );
    }
} 

This is a simple example that handles the form data in an isolated fashion, for a more robust app you may want to use redux and async action creators with thunk middleware.