Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useStorageState #76

Closed
awmleer opened this issue Sep 29, 2019 · 3 comments
Closed

useStorageState #76

awmleer opened this issue Sep 29, 2019 · 3 comments

Comments

@awmleer
Copy link
Collaborator

awmleer commented Sep 29, 2019

支持把 state 支持化的存储在 localStorage 中,例如暂存用户输入的内容,保存用户的设置。

API

function useStorageState<T extends string>(key: string, defaultValue: T): [T, (value: T) => void]

第一个参数为 localStorage 的 key ,第二个参数为 state 的默认值。

返回值的类型和 useState 一致。

Demo

const [input, setInput] = useStorageState('chat-input', '')
@brickspert brickspert added the API label Sep 29, 2019
@ttys026
Copy link
Collaborator

ttys026 commented Oct 6, 2019

我理解既然要保存就不应该在 unmount 的时候 clear 掉 storageState,
是否需要暴露出一个 removeItem 的方法呢?
另外这里是否做成 { value, onChange } 这种形式,可以考虑一下

@awmleer
Copy link
Collaborator Author

awmleer commented Oct 6, 2019

不传参数直接调用 setState() ,或者 setState(undefined) 就是 localStorage.removeItem 。。

@awmleer
Copy link
Collaborator Author

awmleer commented Oct 6, 2019

{ value, onChange } 的感觉不是很有必要。。现在这样的API可以保证和 useState 的兼容性,对用户的使用来说非常友好。如果用户需要监听 state 的变化,那么也可以按照 useState 对应的处理方案,写一个 useEffect

@awmleer awmleer mentioned this issue Oct 9, 2019
@awmleer awmleer closed this as completed Oct 10, 2019
brickspert added a commit that referenced this issue Jun 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants