Last active
August 25, 2023 17:24
-
-
Save itzaks/5422904911268474fbc41416555bbb4a to your computer and use it in GitHub Desktop.
Editable cells for Payload CMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: