import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';

export function usePersistentState(key, defaultValue) {
  const [state, setState] = useState(defaultValue);

  // 初始化时从存储中读取值
  useEffect(() => {
    const loadState = async () => {
      try {
        const { data } = await Taro.getStorage({ key });
        if (data !== undefined) {
          setState(data);
        }
      } catch (err) {
        console.log('读取存储失败:', err);
      }
    };
    loadState();
  }, [key]);

  // 状态变化时同步到存储
  useEffect(() => {
    Taro.setStorage({ key, data: state }).catch(err => {
      console.log('存储失败:', err);
    });
  }, [key, state]);

  return [state, setState];
}
