datatable reading local storage
This commit is contained in:
59
src/lib/contexts/tableSetting.jsx
Normal file
59
src/lib/contexts/tableSetting.jsx
Normal file
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import {createContext, useEffect, useState} from "react";
|
||||
|
||||
export const TableSettingContext = createContext();
|
||||
|
||||
export const TableSettingProvider = ({children}) => {
|
||||
const [settingStore, setSettingStore] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
const _localStorage = localStorage.getItem("_setting-app")
|
||||
if (_localStorage)
|
||||
setSettingStore(JSON.parse(_localStorage))
|
||||
}, []);
|
||||
|
||||
const hideAction = (user_id, page_name, table_name, settingValue) => {
|
||||
updateSettingStorage(user_id, page_name, table_name, "hides", settingValue);
|
||||
}
|
||||
const sortAction = (user_id, page_name, table_name, settingValue) => {
|
||||
updateSettingStorage(user_id, page_name, table_name, "sorts", settingValue);
|
||||
}
|
||||
const filterAction = (user_id, page_name, table_name, settingValue) => {
|
||||
updateSettingStorage(user_id, page_name, table_name, "filters", settingValue);
|
||||
}
|
||||
const updateSettingStorage = (user_id, page_name, table_name, settingType, settingValue) => {
|
||||
const prevLocalStorage = JSON.parse(localStorage.getItem("_setting-app")) || {};
|
||||
const userSettings = prevLocalStorage[user_id] || {};
|
||||
const pageSettings = userSettings[page_name] || {};
|
||||
const tableSettings = pageSettings[table_name] || {};
|
||||
let newSettings;
|
||||
if (settingType === "sorts") {
|
||||
newSettings = [...settingValue];
|
||||
} else {
|
||||
newSettings = {...tableSettings[settingType] || {}, ...settingValue};
|
||||
}
|
||||
const updatedLocalStorage = {
|
||||
...prevLocalStorage,
|
||||
[user_id]: {
|
||||
...userSettings,
|
||||
[page_name]: {
|
||||
...pageSettings,
|
||||
[table_name]: {
|
||||
...tableSettings,
|
||||
[settingType]: Array.isArray(settingValue) ? [...newSettings] : {...newSettings},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
localStorage.setItem("_setting-app", JSON.stringify(updatedLocalStorage));
|
||||
setSettingStore(updatedLocalStorage);
|
||||
}
|
||||
|
||||
return (
|
||||
<TableSettingContext.Provider
|
||||
value={{settingStore, hideAction, sortAction, filterAction}}>
|
||||
{children}
|
||||
</TableSettingContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user