Published: February 08 2023

Vue 3 - HTTP PATCH Request Examples

Tutorial built with Vue 3.2.45 using the Composition API

Below is a quick set of examples to show how to send HTTP PATCH requests from Vue 3 to a backend API using fetch() which comes built into all modern browsers.

Other Vue 3 HTTP examples: GET, POST, PUT, DELETE.

Tutorial contents


Simple HTTP PATCH request with a JSON body

This sends an HTTP PATCH request to the Test JSON API which is a fake online REST API that includes a product details route (/products/{id}) route that responds to PATCH requests with the contents of the request body plus the id property from the URL and an updatedAt date property.

After the JSON data is fetched from the API it is assigned to the product ref variable and the updated date is rendered in the component template.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// Simple PATCH request with a JSON body using fetch
const requestOptions = {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Vue 3 PATCH Request Example' })
};
fetch('https://testapi.jasonwatmore.com/products/1', requestOptions)
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">Simple PATCH Request</h5>
        <div class="card-body">Updated at: {{product?.updatedAt}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-patch-request-examples?file=src%2FPatchRequest.vue


HTTP PATCH request with async/await

This sends the same PATCH request from Vue 3 using fetch, but this version uses a couple of top-level await expressions in the <script setup> block to wait for the promises to return (instead of using the promise then() method as above). The top-level await results in the setup function being compiled as async setup().

NOTE: async components must be wrapped with the Vue 3 <Suspense> component in order to render. Suspense is still an experimental feature at the time I'm writing this so the way it works may change in future. For more info see https://vuejs.org/guide/built-ins/suspense.html.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// PATCH request using fetch with async/await
const requestOptions = {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Vue 3 PATCH Request Example' })
};
const response = await fetch('https://testapi.jasonwatmore.com/products/1', requestOptions);
const data = await response.json();
product.value = data;
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">PATCH Request with Async/Await</h5>
        <div class="card-body">Updated at: {{product?.updatedAt}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-patch-request-examples?file=src%2FPatchRequestAsyncAwait.vue


PATCH request with HTTP headers set

This sends the same PATCH request again from Vue 3 using fetch with a couple of extra headers set, the HTTP Authorization header and a custom header My-Custom-Header.

<script setup>
import { ref } from 'vue';

const product = ref(null);

// PATCH request using fetch with set headers
const requestOptions = {
    method: 'PATCH',
    headers: { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    },
    body: JSON.stringify({ name: 'Vue 3 PATCH Request Example' })
};
fetch('https://testapi.jasonwatmore.com/products/1', requestOptions)
    .then(response => response.json())
    .then(data => product.value = data);
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">PATCH Request with Set Headers</h5>
        <div class="card-body">Updated at: {{product?.updatedAt}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-patch-request-examples?file=src%2FPatchRequestSetHeaders.vue


HTTP PATCH request with error handling

This sends a PATCH request from Vue 3 to an invalid url on the API then assigns the error to the errorMessage ref variable and logs the error to the console.

Error handling with the Fetch API

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block. For more info see Fetch - Error Handling for Failed HTTP Responses and Network Errors.

<script setup>
import { ref } from 'vue';

const product = ref(null);
const errorMessage = ref(null);

// PATCH request using fetch with error handling
const requestOptions = {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Vue 3 PATCH Request Example' })
};
fetch('https://testapi.jasonwatmore.com/invalid-url', requestOptions)
    .then(async response => {
        const isJson = response.headers.get('content-type')?.includes('application/json');
        const data = isJson && await response.json();

        // check for error response
        if (!response.ok) {
            // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
        }

        product.value = data;
    })
    .catch(error => {
        errorMessage.value = error;
        console.error("There was an error!", error);
    });
</script>

<template>
    <div class="card text-center m-3">
        <h5 class="card-header">PATCH Request with Error Handling</h5>
        <div class="card-body">Error message: {{errorMessage}}</div>
    </div>
</template>

Vue 3 fetch component at https://stackblitz.com/edit/vue-3-http-patch-request-examples?file=src%2FPatchRequestErrorHandling.vue

 


Need Some Vue 3 Help?

Search fiverr for freelance Vue 3 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by