mantrajs / meteor-mantra-kickstarter

Kickstart your meteor mantra development
MIT License
184 stars 50 forks source link

How to add delete function in collection view #39

Open iamrobreynolds opened 8 years ago

iamrobreynolds commented 8 years ago

In client/modules/_colors/components/colors/_single.jsx there is a function deleteRecord

What is the appropriate way to use the same function or other functions in the collections view?

iamrobreynolds commented 8 years ago

For those looking for how to write custom functions at the collection view, here is what I found to work.


/*
 * File:   /client/modules/module_name/composers/component_name/collection.jsx
*/
import {useDeps} from 'react-simple-di';
import {composeWithTracker, composeAll} from 'react-komposer';

export const collectionComposer = ({context}, onData) => {
  const {Meteor, Collections} = context();
  if (Meteor.subscribe('_collection_name.list').ready()) {
    const collection = Collections._collection_name.find().fetch();
    onData(null, {collection});
  }
};

export const depsMapper = (context, actions) => ({
  deleteAction: actions._collection_name.delete,
  clearErrors: actions._collection_name.clearErrors,
  context: () => context
});

export default (component) => composeAll(
    composeWithTracker(collectionComposer),
    useDeps(depsMapper)
  )(component);

/*
 * File:   /client/modules/module_name/components/component_name/_collection.jsx
*/
export default class extends React.Component {

  deleteRecord(_id) {
    //console.log('deleteRecord', _id);
    this.props.deleteAction(_id);
  };

  render() {
    const {collection} = this.props;
    return(
      <div>
        <h2>Collection Name</h2>
        <div className="table-responsive">
          <table className="table table-striped table-hover">
            <thead className="thead-inverse">
              <tr>
                <th>&nbsp;</th>
                <th>Title</th>
              </tr>
            </thead>
            <tbody>
              {collection.map(record => (
              <tr key={record._id}>
                <td><button type="button" className="btn btn-danger btn-sm" onClick={() => this.deleteRecord(`${record._id}`)}>x</button></td>
                <td scope="row">
                  <b>{record.title}</b><br />
                  <small><a href={`/_collection_name/${record._id}/edit`}>edit</a> | <a href={`/_collection_name/${record._id}`}>view</a></small>
                </td>
              </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    )
  }

}