Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Router Basics Getting Started with React Router What is Routing?

React and saving data

Can you provide some resources or descriptions around how React interacts with the backend? For example, if you wanted to save the data from the sign up form, what needs to be done?

1 Answer

Stan Day
Stan Day
36,671 Points

Hi Lai, You can bind a function to the sign up form submit event, in that function get the form data and call your backend via ajax. When you get a response you can update state so the ui can show if the sign up was successful or if there is an error like if the username was taken for instance.

import React, { Component } from 'react';
import serialize from 'form-serialize';
import restApi from '../lib/rest-api';

class SignUp extends Component {
  state = {
    errorMessage: null,
  };

  onSubmit = (e) => {
    e.preventDefault();

    const data = serialize(e.target, { hash: true });

    restApi.post('/user', data)
      .then(res => {
        // success
      })
      .catch(err => {
        this.setState({ errorMessage: err });
      });
  };

  render() {
    return (
      <form onSubmit={this.onSubmit} className="SignUp">
        {this.state.errorMessage && (
          <p>{this.state.errorMessage}</p>
        )}
        <input name="name" type="text" placeholder="Name" />
        <input name="email" type="text" placeholder="Email" />
        <input name="password" type="password" placeholder="Password" />
        <button type="submit">Sign Up</button>
      </form>
    )
  }
}

export default SignUp