Best way to push or remove from arrays

default discord avatar
wmcmorrow212 months ago
6

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

  • default discord avatar
    imcorfitz12 months ago

    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
    wmcmorrow212 months ago

    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
    imcorfitz12 months ago

    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
    wmcmorrow212 months ago

    @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 help straight from the Payload team with an Enterprise License.