frisk0k
frisk0k

Reputation: 177

How to load AJAX in react

Im trying to get my json result into my react code

The code looks like the following

_getComments() {

 const commentList = "AJAX JSON GOES HERE"

return commentList.map((comment) => {
  return ( 
           <Comment
           author={comment.author}
           body={comment.body}
           avatarUrl={comment.avatarUrl}
           key={comment.id} />);
  });
}

How do i fetch AJAX into this?

Upvotes: 8

Views: 17939

Answers (4)

tobiasandersen
tobiasandersen

Reputation: 8688

First, to fetch the data using AJAX, you have a few options:

Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:

  1. Fetching initial data (e.g. a list of users).
  2. Fetching data in response to some user interaction (e.g. clicking a button to add more users).

Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      username: '',
      lastGistUrl: ''
    };
  },

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
    return (
      <div>
        {this.state.username}'s last gist is
        <a href={this.state.lastGistUrl}>here</a>.
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);

Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.

Fetching data in response to e.g. an action can be done like this:

var UserGist = React.createClass({
  getInitialState: function() {
    return {
      users: []
    };
  },

  componentWillUnmount: function() {
    this.serverRequest && this.serverRequest.abort();
  },

  fetchNewUser: function () {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      var users = this.state.users
      users.push(lastGist.owner.login)
      this.setState({ users });
    }.bind(this));
  },

  render: function() {
    return (
      <div>
        {this.state.users.map(user => <div>{user}</div>)}
        <button onClick={this.fetchNewUser}>Get new user</button>
      </div>
    );
  }
});

ReactDOM.render(
  <UserGist source="https://api.github.com/users/octocat/gists" />,
  mountNode
);

Upvotes: 12

viktor-zin
viktor-zin

Reputation: 209

You can use jQuery.get or jQuery.ajax in componentDidMount:

import React from 'react';

export default React.createClass({
...
    componentDidMount() {
        $.get('your/url/here').done((loadedData) => {
            this.setState({data: loadedData});
    });
...
}

Upvotes: 1

Golan Kiviti
Golan Kiviti

Reputation: 4255

Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Lets say we want to fetch a simple list into our component.

export default MyComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            lst: []
        };

        this.fetchData = this.fetchData.bind(this);
    }

    fetchData() {
        fetch('url')
        .then((res) => {
            return res.json();
        })
        .then((res) => {
            this.setState({ lst: res });
        });
    }
}

We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.

Upvotes: 4

Leon.cao
Leon.cao

Reputation: 1

First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.

Upvotes: -2

Related Questions