Comments (7)
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.
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.
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.
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.
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.
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.
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)
- Add LICENSE file
- I am facing this issue while using this library HOT 5
- is setState necessary in the updateValue Callback? HOT 1
- Doesn't work for background scripts HOT 1
- Add proper typing support for typescript HOT 1
- Add session storage support
- Create Chrome Storage State Hook Local/Sync wrong type?
- Update Types HOT 2
- Typescript error - must have a '[Symbol.iterator]()' method that returns an iterator. HOT 2
- `createChromeStorageStateHookLocal` knowing when value has been fetched (or none found in storage) HOT 15
- Review and improve typing - index.d.ts
- Uncaught TypeError when running localhost HOT 3
- createChromeStorageStateHookSession actually storing in 'sync' HOT 1
- Stored objects and arrays retrieved as string HOT 2
- createChromeStorageStateHookLocal returns initial value first then the persisted one HOT 3
- chrome.storage.local.get doesn't return the initial values HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from use-chrome-storage.