Issue
I have a problem with the accumulation of query params when I choose a new filter to my select.
How can I keep the current filter with each change ?
Here my select :
import SelectInput from '@/Components/SelectInput';
import { ApplicationData } from '@/types/generated';
import { InertiaFormProps } from '@inertiajs/react/types/useForm';
import { PropsWithChildren } from 'react';
import { ApplicationSlugFilterFormProps } from '../Index';
interface ApplicationSlugFiltersProps extends PropsWithChildren {
applications: ApplicationData[];
form: InertiaFormProps<ApplicationSlugFilterFormProps>;
}
export default function ApplicationFilterSlug({ applications, form }: ApplicationSlugFiltersProps) {
return (
<SelectInput
form="page-filters"
name="filter[group.id]"
value={form.data['filter[application_slug]']}
className="!h-10"
onChange={e => {
form.setData('filter[application_slug]', e.currentTarget.value);
}}
>
<option value="">Tous les groupes</option>
{applications.map(applications => (
<option key={applications.id} value={applications.slug}>
{applications.name}
</option>
))}
</SelectInput>
);
}
The inertia form :
const filterForm = useForm<ApplicationSlugFilterFormProps>({
'filter[name]': queryParameters.get('filter[name]') ?? '',
'filter[application_slug]': queryParameters.get('filter[application_slug]') ?? '',
});
The type used :
export type ApplicationSlugFilterFormProps = {
'filter[name]': string;
'filter[application_slug]': string;
};
My base url :
http://myapp.test/admin/settings/groups
My base url with first filter :
http://myapp.test/admin/settings/groups?filter%5Bname%5D=&filter%5Bapplication_slug%5D=tts
My base path above with a new filter applied :
http://myapp.test/admin/settings/groups?filter%5Bname%5D=&filter%5Bapplication_slug%5D=tts&filter%5Bname%5D=&filter%5Bapplication_slug%5D=workflow
The goal is to make an url look like the second path and not have a duplicate filter at each changes.
Do you have any idea how to do this?
Thank you in advance
Solution
Use URLSearchParams object, part of the URL object.
- parse the URL using
URL
constructor - use the
set
method on the url'ssearchParams
object
The
set()
method of theURLSearchParams
interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it.
- convert the URL object back to a string
// 1
const url = new URL("http://myapp.test/admin/settings/groups?filter%5Bname%5D=&filter%5Bapplication_slug%5D=tts")
// 2
url.searchParams.set("filter[application_slug]", "workflow")
// 3
console.log(String(url))
http://myapp.test/admin/settings/groups?filter%5Bname%5D=&filter%5Bapplication_slug%5D=workflow
Answered By - Mulan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.