Class

useRecord

useRecord

A powerful, hook which allows you to create and save records from the Frontend side.

What does it mean?

Let say you have a record action defined like this:

actions: {
  comment: {
    actionType: 'record',
    component: AdminBro.bundle('./comment-component.tsx'),
  }
},
properties: {
  comment: { type: 'textarea' },
}

And, inside the component, you would like to update a comment property and save it to the database.

You can use useRecord hook to do all of this.

Usage - simplest case.

This is how CommentComponent from the previous example could look like:

import { BasePropertyComponent, useRecord, Box, useTranslation } from '@admin-bro/design-system'

const MyRecordActionComponent = (props) => {
  const { record: initialRecord, resource, action } = props

  const { record, handleChange, submit } = useRecord(initialRecord, resource.id)

  const { translateButton } = useTranslation()

  const handleSubmit = (event) => {
    submit().then((response) => {
       // you can do something like redirect user, or update state of the component
       // `response.data.record` holds the updated record
    })
  }

  return (
    <Box
      as="form"
      onSubmit={handleSubmit}
    >
      <BasePropertyComponent
        where="edit"
        onChange={handleChange}
        property={resource.properties.comment}
        resource={resource}
        record={record}
      />
      <Button variant="primary" size="lg">
        {translateButton('save', resource.id)}
      </Button>
    </Box>
  )
}
export default MyRecordActionComponent

We used useRecord along with BasePropertyComponent which renders input for a given property.

In the first step:

const { record, handleChange, submit } = useRecord(initialRecord, resource.id)

useRecord has been initialized with the initial state returned by AdminBro. It was possible because record actions have the current record in the props. The next argument was the resource.id which tells useRecord where it should send API requests.

You can always put a null there, which will result in an empty record returned. In such case useRecord will try to create it in the first submit call.

Next, in BasePropertyComponent we use handleChange callback which usually takes 2 arguments:

  • path (name) of the field
  • and updated value.

In our case, BasePropertyComponent invokes it with arguments 'comment' and whatever is in the textarea. Base on that useRecord updates record which was returned in the invocation.

To see more information about the possible way of invoking handleChange callback see OnPropertyChange

Finally, this initial state has to be send to the Backend via the API to update the record in DB. It is done with submit() method.

More complicated use cases

That was a simple use case. But this is just the start. You can use useRecord hook to build:

  • complicated custom forms
  • handle one to many relationships
  • filter data send from the frontend
  • and many more.

Check out all the options and see what you can use from the returned object

View Source admin-bro/src/frontend/hooks/use-record/use-record.tsx, line 23

Type Definitions

object

# UseRecordOptions

Custom options passed to useRecord as the third argument.

Example of restricting useRecord to operate only on a finite set of properties:

const { record, handleChange, submit } = useRecord(initialRecord, resource.id, {
  includeParams: ['name', 'surname', 'school.name'],
})

// handleChange('otherProperty', 'value') wont affect the `record`
Properties:
Name Type Attributes Description
includeParams Array.<string> <optional>

If set, useRecord will operate only on selected params. The rules here will be applied to, both initialRecord params and all the params set by handleChange. It wont be applied to params, set in submit

View Source admin-bro/src/frontend/hooks/use-record/use-record.type.ts, line 7

object

# UseRecordResult

Result of useRecord hook

Properties:
Name Type Description
record RecordJSON

recordJSON instance for given resource.

handleChange OnPropertyChange

Function compatible with onChange method supported by all the components wrapped by, BasePropertyComponent.

submit UseRecordSubmitFunction

Triggers submission of the record. Returns a promise.

loading boolean

Flag indicates loading.

progress number

Upload progress

setRecord React.Dispatch.<React.SetStateAction.<RecordJSON>>

Sets value for the record from the outside. You might use it when you update the record, simultaneously in an another place.

isSynced boolean

Indicates if record is in "synced" state. It is when it was either just created from initial, record or submitted. After at least one handleChange it is false until the successful submit

View Source admin-bro/src/frontend/hooks/use-record/use-record.type.ts, line 43

# UseRecordSubmitFunction(customParamsopt, optionsopt)

Submit function which either creates a record or updates it. By default, after successful execution function updates its inner state with the returned by the backend record. This might not be the need in your case, so you can turn it of by setting updateOnSave to false.

Parameters:
Name Type Attributes Description
options.updateOnSave boolean <optional>

Indicates if record should be updated after the submit action, which returns updated record. You might turn this of if you use function like lodash debounce, where you might have old state in the action response.

customParams Record.<string, string> <optional>

Any additional parameters you want to be merged to the payload.

options object <optional>

Custom options passed to submit function

View Source admin-bro/src/frontend/hooks/use-record/use-record.type.ts, line 27

SoftwareBrothers

Proudly built and maintained by SoftwareBrothers

Software House with a passion for both JavaScript and TypeScript.

See what we do See what we believe in

Proudly built and maintained by

SoftwareBrothers