From 53573a99bf1972b8dfeec45b3246c9b8fb39fbf5 Mon Sep 17 00:00:00 2001 From: Aleksandr Smyshliaev Date: Sat, 16 Nov 2024 02:41:47 +0400 Subject: [PATCH] docs: Update README.md --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/README.md b/README.md index 014f578..7286671 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,55 @@ function MyComponent() { } ``` +#### Custom hook to work with slice of state conveniently +
+ Example + + ```typescript +'use client'; + +import React from 'react'; +import { useUrlState } from 'state-in-url/next'; + +const form: Form = { + name: '', + age: undefined, + agree_to_terms: false, + tags: [], +}; + +type Form = { + name: string; + age?: number; + agree_to_terms: boolean; + tags: {id: string; value: {text: string; time: Date } }[]; +}; + +export const useFormState = ({ searchParams }: { searchParams?: object }) => { + const { urlState, setUrl: setUrlBase, reset } = useUrlState(form, { + searchParams, + }); + + // first navigation will push new history entry + // all following will just replace that entry + // this way will have history with only 2 entries - ['/url', '/url?key=param'] + + const replace = React.useRef(false); + const setUrl = React.useCallback(( + state: Parameters[0], + opts?: Parameters[1] + ) => { + setUrlBase(state, { replace: replace.current, ...opts }); + replace.current = true; + }, [setUrlBase]); + + return { urlState, setUrl, resetUrl: reset }; +}; + ``` +
+ +
+ #### With complex state shape