Skip to content

Commit

Permalink
enh(useFetch, ):
Browse files Browse the repository at this point in the history
- Adds the  function that returns all searchParams
- Enhances the useFetch function: the submit() method can be used with any data type
  • Loading branch information
danybeltran committed Jul 8, 2024
1 parent f72fd8f commit f774c22
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "http-react",
"version": "3.6.2",
"version": "3.6.3",
"description": "React hooks for data fetching",
"main": "dist/index.js",
"scripts": {
Expand Down
22 changes: 14 additions & 8 deletions src/hooks/use-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
getRequestHeaders,
hasBaseUrl,
isDefined,
isFormData,
isFunction,
jsonCompare,
notNull,
Expand Down Expand Up @@ -1542,18 +1543,23 @@ export function useFetch<FetchDataType = any, BodyType = any>(

const submit = useCallback(
(form: FormData) => {
if (formRef.current) {
if (onSubmit) {
if (onSubmit !== 'reset') {
onSubmit(formRef.current, form)
} else {
if (formRef.current) {
formRef.current.reset()
if (isFormData(form)) {
if (formRef.current) {
if (onSubmit) {
if (onSubmit !== 'reset') {
onSubmit(formRef.current, form)
} else {
if (formRef.current) {
formRef.current.reset()
}
}
}
}
}
temporaryFormData.set(resolvedKey, form)
temporaryFormData.set(
resolvedKey,
isFormData(form) ? form : serialize(form)
)
reValidate()
},
[resolvedKey, formRef.current, reValidate]
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ export {
actionResult,
actionData,
$form,
$formData,
$searchParams,
jsonCompare,
windowExists
windowExists,
queue
} from './utils/shared'
23 changes: 23 additions & 0 deletions src/utils/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,29 @@ export function $form<T = any>(form: FormData) {
return Object.fromEntries(form.entries()) as T
}

export const $formData = $form

export function $searchParams<T = any>(input: string) {
const searchParams = new URL(input).searchParams

const allKeys = searchParams.keys()

const parsedParams = new Map()

// @ts-expect-error
for (let key of allKeys) {
const allValues = searchParams.getAll(key)

if (allValues.length > 1) {
parsedParams.set(key, allValues)
} else {
parsedParams.set(key, allValues[0])
}
}

return Object.fromEntries(parsedParams.entries()) as T
}

/**
* Creates a new request function. This is for usage with fetcher and fetcher.extend
*/
Expand Down

0 comments on commit f774c22

Please sign in to comment.