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.

Best way to push or remove from arrays

default discord avatar
wmcmorrow2last year
6

How might I push or pull from an array using a patch REST query?

  • default discord avatar
    imcorfitzlast year

    I believe array fields should be considered fields as any other field type - meaning that you don't post an add or remove event of individual array items - rather you post how the new entire array should look like.



    So if for example you have an array from the API Get like this:

    [1,2,3,4]

    and you want to remove

    3

    - you would send a

    patch

    event where you would set your array value to

    [1,2,4]

    . If you want to add

    5

    you would send a patch event with array value:

    [1,2,3,4,5]
  • default discord avatar
    wmcmorrow2last year

    I see, thanks for that! It's pity there's equivalent of $push or $pull so that you could edit pre-populated arrays without processing the objects back into strings on the front end

  • default discord avatar
    imcorfitzlast year

    Well - in theory, you could extend the api and create your own resolver that does it

    https://payloadcms.com/docs/graphql/extending



    So you could create a GraphQL mutation thats called

    addItemToMyArray(...data)

    and then your resolver takes care of the merging locally.



    You can do the same for REST:

    https://payloadcms.com/docs/rest-api/overview#custom-endpoints
  • default discord avatar
    wmcmorrow2last year

    @imcorfitz Great, I'll check this out

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..