Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load AJAX in react

Tags:

ajax

reactjs

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?

like image 297
frisk0k Avatar asked Aug 21 '16 17:08

frisk0k


2 Answers

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

  • The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
  • A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
    • superagent
    • reqwest
    • react-ajax
    • axios
    • request

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
);
like image 199
tobiasandersen Avatar answered Oct 03 '22 17:10

tobiasandersen


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.

like image 36
Golan Kiviti Avatar answered Oct 03 '22 18:10

Golan Kiviti