Skip to content

Instantly share code, notes, and snippets.

@itzaks
Last active August 25, 2023 17:24
Show Gist options
  • Select an option

  • Save itzaks/5422904911268474fbc41416555bbb4a to your computer and use it in GitHub Desktop.

Select an option

Save itzaks/5422904911268474fbc41416555bbb4a to your computer and use it in GitHub Desktop.
Editable cells for Payload CMS
import React from "react";
import { useRef, useState, useEffect } from "react"
import { type Props } from "payload/components/views/Cell"
import { useConfig } from "payload/dist/admin/components/utilities/Config"
const DEBOUNCE_UPDATE_MS = 1500
const EditableTextCell: React.FC<Props> = (props) => {
const { field, collection, cellData, rowData } = props
const [cellValue, setCellValue] = useState(String(cellData))
const config = useConfig()
const isFirstRun = useRef(true)
const { slug } = collection
const { serverURL, routes: { api } } = config;
const id = String(rowData.id)
const url = `${serverURL}${api}/${slug}/${id}`
// Debounce fetch calls
useEffect(() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return
}
const getData = setTimeout(() =>
fetch(url, {
method: "PATCH",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
[field.name]: cellValue
}),
})
, DEBOUNCE_UPDATE_MS)
return () => clearTimeout(getData)
}, [cellValue])
const onInputUpdate = (event) => {
setCellValue(event.target.value)
}
return (
<input onChange={onInputUpdate} value={cellValue} onBlur={onInputUpdate} />
)
}
export default EditableTextCell
@itzaks
Copy link
Author

itzaks commented Aug 25, 2023

Usage:

  fields: [
    {
      name: 'name',
      type: 'text',
      required: true,
      admin: {
        components: {
          Cell: CustomCell
        },
      },
   ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment