0.1.12 • Published 5 years ago

react-crud-hook v0.1.12

Weekly downloads
375
License
ISC
Repository
github
Last release
5 years ago

react-crud-hook

React hook for CRUD-operations and record state management.

This package attempts to make it easier to perform CRUD-operations while also providing methods to set attributes and relationships on a record. Records should conform to the JSON:API specs - https://jsonapi.org/. The react-crud-hook package is fully typed and optimized to prevent unnecessary renders.

Installation

npm

npm install --save react-crud-hook

yarn

yarn add react-crud-hook

API

CrudManager

import { CrudManager } from 'react-crud-hook'

// First create a CRUD manager.
// The CRUD manager takes a single object with a promise for the createRecord, 
// updateRecord and deleteRecord attributes.
// You can use the extensions attribute to provide an object with custom extensions that
// will be returned in several callbacks later on as you perform CRUD-operations.
const manager = new CrudManager({
  createRecord: Promise<Record>,
  updateRecord: Promise<Record>,
  deleteRecord: Promise<RecordIdentifier>
  extensions: {
    dispatch: redux.dispatch,
    router: react.router,
    modal: modal
  }
})

Store

import { Store, Dispatcher, Reducer } from 'react-crud-hook'

// The store is not required as it is already provided by default. However if you like to customize how records are
// updated in the store you can provide your own Dispatcher and/or Reducer. 

const store = new Store({
  dispatcher: new Dispatcher(),
  reducer: new Reducer()
})

<CrudProvider/>

By default the provider will have a store, where it manages records and subscriptions. However, you can also pass one yourself.

import { CrudProvider } from 'react-crud-hook'

// Store is not required - it will have one by default
ReactDOM.render(
  <CrudProvider manager={manager} store={Store}>
    <App/>
  </CrudProvider>,
  rootElement
)

useCrud(record, options?)

import { useCrud } from 'react-crud-hook'

const record = {
  type: 'user',
  id: '1',
  attributes: {
    name: 'Exivity'
  }
}

const ReactComponent = () => {
  const record = useCrud(record)

  // Perform mutations on mount
  useEffect(() => {
    record
      .setAttribute('name', 'Exivity rocks!')
      .setAttribute('age', 2)
      .addHasMany('employees', { type: 'employee', id: '2' })
      .addHasMany('clients', { type: 'client', id: '7' })
      .addHasOne('CEO', { type: 'CEO', id: '2' })
      .resetAttributes('age')
      .save({ 

        // Use standard callback enriched with extensions to perform side tasks
        beforeUpdate: (record, extensions) => {
          return extensions.modal('Are you sure you want to proceed with this update?')
        },
        onUpdate: (record, extensions) => {
          extensions.router.push(`/user/${user.id}`)
        }

        // You can also include custom properties that will be passed on to the CRUD-functions 
        // as second argument, such as a include property:
        include: {
          .........
        }
      })
  }, [record.id])
   // State is managed via a functional pattern so you do not have to worry about race conditions etc. 
   // Make sure to use the id instead of record itself as dependencies for useEffect as the record will have a new reference
   // after you call a method on it. Also, if you rely on record attributes or relations in your effect, do not forget to put those
   // in dependencies array.

  // Or perform mutations on events
  return (
    <div>
      <input value={record.attributes.name}
        onChange={(e) => record.setAttribute('name', e.target.value)}/>
      <button onClick={record.save}> Click </button>
    </div>
  )
  
    // Use curried methods
    return (
      <div>
        <input value={record.attributes.name}
          onChange={record.setAttribute('name')}/>
        <button onClick={record.save}> Click </button>
      </div>
    )
}

options?

NamevalueDescription
unSubscribeDelaynumberWhen useCrud unmounts it deletes the associated record state from store - you can delay this with this option.
onUnSubscribe(record) => voidThis callback will be called when a record unSubscribes from store. Normally this happens when useCrud unmounts unless the unSubscribeDelay option has been given.

Methods

All the following methods, except for save and delete, can be curried by providing only the first argument.

NameParametersDescription
setAttributeattribute, valueUse setAttribute to update a record attribute.
addHasManyrelationship, RecordIdentifierUse addHasMany to add a hasMany related record.
addHasOnerelationship, RecordIdentifierUse addHasOne to add or replace a hasOne related record.
removeRelationshiprelationship, relatedIdUse removeRelationship to remove a hasOne or hasMany related record.
resetnoneUse reset to reset all attributes and relationships to its initial value.
resetAttributesstring or string[]Use resetAttributes to specifically reset attributes only.
resetRelationshipsstring or string[]Use resetRelationships to specifically reset relationships only.
saveoptions?Use save to persist a record - save will determine by the presence of an id whether to create or update. Alongside of the standard callbacks you can provide custom options which will be passed to the provider crud-functions as second argument.
deleteoptions?Use delete to delete a record.

Parameter types

ParameterType
attributestring
valueany
relationshipstring
RecordIdentifier{ id: string, type: string }
RelatedIdstring
options{ ...standardCallbacks, ...customOptions }

Standard callbacks and custom options

Callbacks are handled by the manager and enriched with the extensions you provide to the CrudManager. Custom options are passed to each crud function (provided to the CrudManager) as second argument. You can use the following callbacks:

CallbackargumentsDescription
beforeCreaterecord, extensionsYou can return a Promise that either returns a new record which it then will use for the create operation or a truthy or falsy value. Instead of a Promise you can also just directly return a truthy/falsy value A truthy value will let the operation proceed and a falsy value will abort it.
onCreaterecord, extensionsonCreate will be called on fulfillment of the operation.
beforeUpdaterecord, extensionsWorks like beforeCreate.
onUpdaterecord, extensionsWorks like onCreate.
beforeDeleterecord, extensionsWorks like beforeCreate.
onDeleterecordIdentifier, extensionsWorks like onCreate.
onErrorerror, record, extensionsIf a operation (promise) catches, onError will be called.

License

MIT

0.1.12

5 years ago

0.1.11

5 years ago

0.1.10

5 years ago

0.1.9

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.56

5 years ago

0.0.55

5 years ago

0.0.54

5 years ago

0.0.53

5 years ago

0.0.52

5 years ago

0.0.51

5 years ago

0.0.50

5 years ago

0.0.49

5 years ago

0.0.48

5 years ago

0.0.47

5 years ago

0.0.46

5 years ago

0.0.45

5 years ago

0.0.44

5 years ago

0.0.43

5 years ago

0.0.42

5 years ago

0.0.41

5 years ago

0.0.40

5 years ago

0.0.39

5 years ago

0.0.38

5 years ago

0.0.37

5 years ago

0.0.36

5 years ago

0.0.35

5 years ago

0.0.34

5 years ago

0.0.33

5 years ago

0.0.32

5 years ago

0.0.31

5 years ago

0.0.30

5 years ago

0.0.29

5 years ago

0.0.28

5 years ago

0.0.27

5 years ago

0.0.26

5 years ago

0.0.25

5 years ago

0.0.24

5 years ago

0.0.23

5 years ago

0.0.22

5 years ago

0.0.21

5 years ago

0.0.20

5 years ago

0.0.19

5 years ago

0.0.18

5 years ago

0.0.17

5 years ago

0.0.16

5 years ago

0.0.15

5 years ago

0.0.14

5 years ago

0.0.13

5 years ago

0.0.12

5 years ago

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago