aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

Support for creating/deleting relationships #23

Closed firstgeneration closed 3 years ago

firstgeneration commented 3 years ago

Is there a way to use useMutation or useClient to achieve a relationship creation/deletion, shown below? Thank you!

POST or DELETE /articles/1/relationships/comments HTTP/1.1

{
  "data": [
    { "type": "comments", "id": "123" }
  ]
}
aribouius commented 3 years ago

@firstgeneration haven't tested this, but it does look like the serializer handles arrays. Give one of these approaches a try:

function approach1() {
  const [mutate] = useMutation('articles/1/relationships/comments')

  const onSubmit = () => {
    mutate([{ id: 123 }])
  }
}

function approach2() {
  const client = useClient()

  const onSubmit = () => {
    client.mutate('articles/1/relationships/comments', [{ id: 123 }])
  }
}