Skip to content

Commit

Permalink
docs: Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
asmyshlyaev177 authored Nov 15, 2024
1 parent f0a3d54 commit 53573a9
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,55 @@ function MyComponent() {
}
```

#### Custom hook to work with slice of state conveniently
<details>
<Summary>Example</Summary>

```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<typeof setUrlBase>[0],
opts?: Parameters<typeof setUrlBase>[1]
) => {
setUrlBase(state, { replace: replace.current, ...opts });
replace.current = true;
}, [setUrlBase]);

return { urlState, setUrl, resetUrl: reset };
};
```
</details>

<hr />

#### With complex state shape

<details>
Expand Down

0 comments on commit 53573a9

Please sign in to comment.