Ad

Reactjs: Loading View Based On Response

- 1 answer

Looking for a way for React to process some json, and load views based on the response.

For example:

1- React has a form, response goes out to external API

2- API processes the input, returns a success code unless there was validation issues, and send a response back to the React app

3- React gets the json response, loads a "Success" view, or reloads the form and outputs the erros

Is there a simple way for React to handle this? Thanks in advance!

Ad

Answer

Very simple...

Basically, you need to track when you initiate request (sending data) and when request is completed (receiving response).

Based on data returned, you decide what to render...
Take a look at this example (working fiddle)

// In this example, we are using JSONPlaceholer service do real
// request and receive response;
const root = 'http://jsonplaceholder.typicode.com';

const Success = () => (<div>Success!</div>);

const Error = () => (<div>Error! Fix your data!</div>);

const Form = React.createClass({
  getInitialState() {
    return {
      processing: false,
      result: undefined,
    };
  },

  submit(event) {
    this.setState({ processing: true });
    event.preventDefault();

    fetch(`${root}/posts`, {
      method: 'POST',
      data: {
        // your data here...
      }
    })
      .then(response => {
        // We simulate succesful/failed response here.
        // In real world you would do something like this..
        // const result = response.ok ? 'success' : 'error';

        const processing = false;
        const result = Math.random() > 0.5 ? 'success' : 'error';
        this.setState({ result, processing });
      });
  },

  render() {
    const { result, processing } = this.state;

    if (result === 'success')
        return <Success />;

    return (
      <form>
        Form content here<br/>
        <button onClick={this.submit}>
          { processing ? 'Sending data...' : 'Submit' }
        </button>
        { result === 'error' && <Error /> }
      </form>
    );
  },
});

render(<Form />, document.getElementById('root'));
Ad
source: stackoverflow.com
Ad