Skip to content

Instantly share code, notes, and snippets.

@ArnaudRinquin
Last active June 14, 2016 10:09
Show Gist options
  • Save ArnaudRinquin/f9a8027e6a1d7000eba4 to your computer and use it in GitHub Desktop.
Save ArnaudRinquin/f9a8027e6a1d7000eba4 to your computer and use it in GitHub Desktop.
The API layer we want
// This one is more or less what you could do in angular 2
import { getUsers } from './userAPI';
import { Component } from 'angular2';
@Component({
template: '<pre>{{this.users}}</pre>'
});
export class UserList {
constructor() {
// for sake of example only, don't call APIs in constructors
// or store stuff within component
getUsers().then(this.setUsers);
}
setUsers = (users) {
// Does following line trigger diggest loop? I guess not
this.users = users;
}
}
// This one is more or less what you could do in react
import { getUsers } from './userAPI';
import { Component } from 'react';
export class UserList extends Component{
constructor() {
this.state = {
users: null
};
}
componentWillMount() {
getUsers().then(this.setUsers);
}
setUsers = (users) {
this.setState({
users
});
}
render() {
const { users } = this.state;
return (<pre>{users}</pre>)
}
}
// A completely independent + framework agnostic API layer
export function getUsers() {
return fetch('/users')
.then(response => response.json())
}
export function getUser(userId) {
return fetch(`/users/${userId}`)
.then(response => response.json())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment