First of all, we have to create our Model
class from ReactResource
factory:
const ModelName = new ReactResource(url, [mappings, [actions]])
- url - {string} - Api endpoint url
'/api/users/{:urlVariable}/?format=json'
- mappings - {Object} - Replace variables in url by values of model instance
{ instanceAttribute: ':urlVariable'}
- actions - {Object} - Add new actions or override default ones
{ actionName: actionConfig }
Also we can extend Model
with custom instance/prototype methods
Don't use ARROW FUNCTION! Use FUNCTION EXPRESSION instead!
import ReactResource from 'react-resource';
/**
* Model class definition
*/
const User = new ReactResource('/api/users/{:id}.json', { id: ':id' })
/**
* Custom instance method
*/
// [OK]
User.prototype.getName = function() {
return [this.first_name, this.last_name].join(" ");
};
// [WRONG] Will not work!
User.prototype.getName = () => [this.first_name, this.last_name].join(" ");
/**
* Get user
*/
User.get({ id: 1 }, (user) => {
console.log('User name is', user.getName());
});