Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,802 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