Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Last active May 25, 2018 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DesignByOnyx/83fb62f641ddaf649e08d5d8b58e7d05 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/83fb62f641ddaf649e08d5d8b58e7d05 to your computer and use it in GitHub Desktop.
This is an attempt to describe a model layer for ylem
  1. Define your models with a transport (this is just sugar for can-connect)

    import { Model,  transport } from 'ylem-model';
    
    const Person = Model({
      id: { type: 'number', identity: true },
      name: { type: 'string' },
      email: { type: 'string' },
      age: { type: 'number' },
    });
    
    export default transport(Person, {
      url: '/api/person'
    });
  2. Use the dataProvider to provide data to your components.

    dataProvider(Model, property, Component);

    The dataProvider generates a HoC which will load data (using an optional query) and provide the results to the underlying component. The results will be exposed on the "property" specifed (the second param to the dataProvider function). The intermediate states are handled for you (loading, error, no data). The underlying component is only rendered when the data loads successfully.

    import React from 'react';
    import { dataProvider } from 'ylem-model';
    import Person from './person';
    
    const Individual = dataProvider(Person, 'person', ({ person }) => {
        return <div>{person.name} is {person.age} years old.</div>;
    });
    
    @dataProvider(Person, 'people')
    class PersonList extends React.Component {
      render() {
        const { people } = this.props;
        <ul>
          {people.map(person => (
            <li key={person.id}><Individual person={person} /></li>
          ))}
        </ul>
      }
    };
    
    export { Individual, PersonList };
  3. Use the component like this, pass a query for filtering

    // Load a single person
    <Individual query={{ id: 1234 }} />
    
    // Load a list of people
    <PersonList query={{ age: { $gt: 27 } }} />
    
    // Pass data directly to bypass loading data:
    <Individual person={{ name: 'Justin', age: 35 }} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment