Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How do I only save changes to a custom component's value on save? [v3.0.0-beta.20]

default discord avatar
tsfosterlast year
5

Hi,



I'm trying to create my first custom component on the v3 beta. if I use

useField()

, changes are saved on every use of

setValue

. I'm guessing I need to use React's

useState()

instead, but I can't work out how to then save the changes when hitting the document's 'Save' button.

  • default discord avatar
    notchrlast year
    @878205106531762176

    Hey, can you post your component code please?



    Ill check it out

  • default discord avatar
    tsfosterlast year

    Thanks

    @1049775120559898725

    .



    src/fields/TestField/Testfield.tsx:


    'use client';
    import {useField} from '@payloadcms/ui/forms/useField'
    
    function TestField({path}) {
      const {value, setValue} = useField({path})
      const onClick = function () {
        setValue(value + '*');
      }
      return (
        <div>
          <button onClick={onClick}>Click me</button><p>{value}</p>
        </div>
      )
    }
    
    export default TestField


    src/fields/TestField/index.ts:


    import Component from './TestField'
    
    export const TestField = (name) => {
      return [{
        name,
        type: 'text',
        admin: {
          components: {
            Field: Component,
          },
        },
      }]
    }


    src/collections/Examples/index.ts:


    import type {CollectionConfig} from 'payload/types'
    import {TestField} from '@/fields/TestField'
    
    export const Examples: CollectionConfig = {
      slug: 'examples',
      admin: {
        useAsTitle: 'name',
      },
      fields: [
        {
          name: 'name',
          type: 'text',
          required: true,
        },
        ...TestField('columname')
      ],
    }
  • default discord avatar
    notchrlast year
    @878205106531762176

    Can you add "type='button'" to your button



    Any buttons without that type will be treated as Submit buttons IIRC



    Which will submit the doc through the normal means

  • default discord avatar
    tsfosterlast year

    🤦‍♂️ Thank you, much appreciated!

  • default discord avatar
    notchrlast year

    Did that solve it?



    Yayyy

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.