Skip to content

useInputHistory

输入记录

text
import { useEffect, useState } from 'react'

const InputHistory = {
  max: 5,
  getList(key: string): string[] {
    const list = localStorage.getItem(key)
    if (list) {
      return JSON.parse(list)
    } else {
      return []
    }
  },
  pushItem(key: string, value: any): void {
    const list = InputHistory.getList(key) || []
    list.unshift(value)
    localStorage.setItem(
      key,
      JSON.stringify([...new Set(list)].slice(0, InputHistory.max))
    )
  },
}

export const useInputHistory = (
  key: string,
  defaultList = []
): [string[], (value: string) => void] => {
  const [list, setList] = useState<string[]>([])

  const setDisplayList = (list: string[]) => {
    if (list.length) {
      setList(list)
    } else {
      setList(defaultList)
    }
  }

  const initHistoryList = () => {
    const history = InputHistory.getList(key)
    if (history) {
      setDisplayList(history)
    }
  }

  useEffect(() => {
    initHistoryList()
  }, [key])

  const pushItem = (value: string) => {
    if (value) {
      InputHistory.pushItem(key, value)
      initHistoryList()
    }
  }

  return [list, pushItem]
}

Example:

text
const [searchList, setSearchList] = useInputHistory('search_user')

Contributors

作者:Long Mo
字数统计:119 字
阅读时长:1 分钟
Long Mo
文章作者:Long Mo
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Longmo Docs