export const useUrlQueryParam = <K extends string>(keys: K[]) => {
const [searchParams] = useSearchParams();
const setSearchParams = useSetUrlSearchParam();
const [stateKeys] = useState(keys);
return [
useMemo(
() =>
subset(Object.fromEntries(searchParams), stateKeys) as {
[key in K]: string;
},
[searchParams, stateKeys]
),
(params: Partial<{ [key in K]: unknown }>) => {
return setSearchParams(params);
// iterator
// iterator: https://codesandbox.io/s/upbeat-wood-bum3j?file=/src/index.js
},
] as const;
};
export const useSetUrlSearchParam = () => {
const [searchParams, setSearchParam] = useSearchParams();
return (params: { [key in string]: unknown }) => {
const o = cleanObject({
...Object.fromEntries(searchParams),
...params,
}) as URLSearchParamsInit;
return setSearchParam(o);
};
};
export const useProjectsSearchParams = () => {
const [param, setParam] = useUrlQueryParam(["name"]);
return [
useMemo(
() => ({ ...param}),
[param]
),
setParam,
] as const;
};
export const useEditProject = () => {
const client = useHttp();
const queryClient = useQueryClient();
const [searchParams] = useProjectsSearchParams()
console.log(searchParams)
//const queryKey = ['projects', searchParams]
const result = useMutation((params: Partial<Project>) => client(`projects/${params.id}`, {
data: params,
method: 'PATCH'
}), {
onSuccess: () => queryClient.invalidateQueries('projects'),
// async onMutate(target) {
// const previousItems = queryClient.getQueryData(queryKey)
// queryClient.setQueryData(queryKey, (old?: Project[]) => {
// return old?.map(project => project.id === target.id ? {...project, ...target} : project) || []
// })
// return {previousItems}
// },
// onError(error, newItem, context) {
// queryClient.setQueryData(queryKey, (context as { previousItems: Project[] }).previousItems)
// }
})
return result
}
解锁 React17 高阶用法,轻松应对大型复杂长周期项目
了解课程