Giter VIP home page Giter VIP logo

Comments (7)

onikienko avatar onikienko commented on May 24, 2024 1

The initialValue does not set value in chrome.storage.local. It works exactly like chrome.storage.local.get({someKey: 'initialValue'}). I do not know the reason why you may need to store 'initialValue' to store.

Usually, it looks like:

export const App = () => {
    const [projectList, setProjectList] = useChromeStorageLocal(AJAX_INTERCEPTOR_PROJECTS, [{
        'pathUrl': 'localhost:3000',
        'rules': [],
    }]);
    const [currentProject, setCurrentProject] = useChromeStorageLocal(AJAX_INTERCEPTOR_CURRENT_PROJECT, 'localhost:3000');

    useEffect(() => {
        console.log(projectList); // it will be [{'pathUrl': 'localhost:3000', 'rules': []}]
        console.log(currentProject); // it will be 'localhost:3000'
    }, []);

    return (
        <>
            <div>
                currentProject: {currentProject}
            </div>
        </>
    );
};

But if for some reason you still want to store the initial value in storage you should not use 'initialValue' during initialization but check for undefined in effect hook and set value. I still can't imagine why you need it but the code may look like this:

export const App = () => {
    const [projectList, setProjectList] = useChromeStorageLocal(AJAX_INTERCEPTOR_PROJECTS);
    const [currentProject, setCurrentProject] = useChromeStorageLocal(AJAX_INTERCEPTOR_CURRENT_PROJECT);

    useEffect(() => {
        if (projectList === undefined) setProjectList([{
            'pathUrl': 'localhost:3000',
            'rules': [],
        }]);
    }, [projectList]);

    useEffect(() => {
        if (currentProject === undefined) setCurrentProject('localhost:3000');
    }, [currentProject]);

    return (
        <>
            <div>

                currentProject: {currentProject}
            </div>
        </>
    );
};

from use-chrome-storage.

onikienko avatar onikienko commented on May 24, 2024 1

I want to give the user a default value as a reference, nothing will make the user feel overwhelmed

Exactly. But there is no need to store this default value in storage. It will be used from your code.
Anyway.

from use-chrome-storage.

botshen avatar botshen commented on May 24, 2024 1

My other components depend on stroage, and if I just use the defaults here and don't put them in stroage, my other logic reading stroage won't be able to read them, and the plugin won't work properly, which is why I need to put the defaults into stroage

from use-chrome-storage.

onikienko avatar onikienko commented on May 24, 2024 1

I see. Good to know such a case. In my code, I usually have constants with default values which I import in components where required.
Anyway. I got your point. Thank you for the explanation.

from use-chrome-storage.

onikienko avatar onikienko commented on May 24, 2024

The second parameter is initialValue - the value used if chrome.storage.local has no stored value yet. And it works as expected.

For your code. It is hard to say from where the error is coming. The first thing to check is the dependencies array in your useEffect hook. It's empty but depends on state changes. And the whole hook looks strange.

from use-chrome-storage.

botshen avatar botshen commented on May 24, 2024

What I'm trying to do is get the value inside the stroge when the component is first rendered, and if it doesn't have it, set it, and if it does have it, use it.

from use-chrome-storage.

botshen avatar botshen commented on May 24, 2024

Thank you for your answer, your code works, the reason for this is that my data needs to be stored in the local, if there is no value at the beginning, I want to give the user a default value as a reference, nothing will make the user feel overwhelmed, after submitting this issue I wrote a method to achieve the functionality that I want, but did not use your library, I will consider better use of yours to I will consider using your library better to increase my efficiency!
this is my code:

export function getOrCreateLocalStorageValues(keyValueMap: KeyValueMap, callback: CallbackType) {
  // 尝试从chrome.storage.local中获取指定键的值
  chrome.storage.local.get(Object.keys(keyValueMap), function (result) {
    if (chrome.runtime.lastError) {
      // 发生错误
      console.error(chrome.runtime.lastError);
      callback(keyValueMap); // 返回初始值映射对象
    } else {
      const updatedValues: KeyValueMap = {};

      // 遍历键值映射对象,检查每个键的值是否存在
      for (var key in keyValueMap) {
        if (key in result) {
          // 如果存在,将其添加到更新后的值映射对象中
          updatedValues[key] = result[key];
        } else {
          // 如果不存在,将初始值设置到chrome.storage.local中
          updatedValues[key] = keyValueMap[key];
          const data: KeyValueMap = {};
          data[key] = keyValueMap[key];
          chrome.storage.local.set(data, function () {
            if (chrome.runtime.lastError) {
              // 发生错误
              console.error(chrome.runtime.lastError);
            }
          });
        }
      }

      // 返回所有键的最新值映射对象
      callback(updatedValues);
    }
  });
}

this is use

  useEffect(() => {
    getOrCreateLocalStorageValues({
      [AJAX_INTERCEPTOR_CURRENT_PROJECT]: 'http://localhost:5173',
      [AJAX_INTERCEPTOR_PROJECTS]: [{
        pathUrl: 'http://localhost:5173',
        rules: [{
          name: 'test',
          code: '200',
          switchOn: true,
          delay: '0',
          method: 'POST',
          pathRule: '/api/test',
          Response: {
            code: 200,
            data: {},
            message: 'success'
          },
        }],
        projectName: '默认项目',
        switchOn: true
      }],
      mockPluginSwitchOn: true,
    }, function (values) {
      const checked = values.mockPluginSwitchOn
      setDefaultChecked(checked)
      if (checked) {
        chrome.action.setIcon({ path: '/images/app.png' });
      } else {
        chrome.action.setIcon({ path: '/images/gray.png' });
      }
      setItems(values[AJAX_INTERCEPTOR_PROJECTS].map((item: any) => {
        return {
          key: item.pathUrl,
          label: item.projectName,
          children: <Table
            columns={columns}
            size='small'
            dataSource={item.rules} />,
        }
      }))
      setDefaultActiveKey(() => values[AJAX_INTERCEPTOR_CURRENT_PROJECT])
      setPreviousActiveKey(() => values[AJAX_INTERCEPTOR_CURRENT_PROJECT])

    })
  }, [])

from use-chrome-storage.

Related Issues (17)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.