Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3d29c16

Browse files
WingSMCGergely Dremakantfu
authored
feat(useFetch): infer 'json' type for array payloads (#4329)
Co-authored-by: Gergely Dremak <[email protected]> Co-authored-by: Anthony Fu <[email protected]>
1 parent 618aabd commit 3d29c16

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

packages/core/useFetch/index.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,22 @@ describe.skipIf(isBelowNode18)('useFetch', () => {
8484
})
8585
})
8686

87+
it('should use \'json\' payloadType', async () => {
88+
let options: any
89+
const payload = [1, 2]
90+
useFetch('https://example.com', {
91+
beforeFetch: (ctx) => {
92+
options = ctx.options
93+
},
94+
}).post(payload)
95+
96+
await retry(() => {
97+
expect(fetchSpy).toHaveBeenCalledOnce()
98+
expect(options.body).toEqual(JSON.stringify(payload))
99+
expect(options.headers['Content-Type']).toBe('application/json')
100+
})
101+
})
102+
87103
it('should have an error on 400', async () => {
88104
const { error, statusCode } = useFetch('https://example.com?status=400')
89105

packages/core/useFetch/index.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -419,9 +419,10 @@ export function useFetch<T>(url: MaybeRefOrGetter<string>, ...args: any[]): UseF
419419
if (config.payload) {
420420
const headers = headersToObject(defaultFetchOptions.headers) as Record<string, string>
421421
const payload = toValue(config.payload)
422-
// Set the payload to json type only if it's not provided and a literal object is provided and the object is not `formData`
422+
// Set the payload to json type only if it's not provided and a literal object or array is provided and the object is not `formData`
423423
// The only case we can deduce the content type and `fetch` can't
424-
if (!config.payloadType && payload && Object.getPrototypeOf(payload) === Object.prototype && !(payload instanceof FormData))
424+
const proto = Object.getPrototypeOf(payload)
425+
if (!config.payloadType && payload && (proto === Object.prototype || Array.isArray(proto)) && !(payload instanceof FormData))
425426
config.payloadType = 'json'
426427

427428
if (config.payloadType)
@@ -592,7 +593,7 @@ export function useFetch<T>(url: MaybeRefOrGetter<string>, ...args: any[]): UseF
592593

593594
function waitUntilFinished() {
594595
return new Promise<UseFetchReturn<T>>((resolve, reject) => {
595-
until(isFinished).toBe(true).then(() => resolve(shell)).catch(error => reject(error))
596+
until(isFinished).toBe(true).then(() => resolve(shell)).catch(reject)
596597
})
597598
}
598599

0 commit comments

Comments
 (0)