I am building a notes app. I want to save the notes entered by the user in the Local Storage so that I can get it even after I refresh my page. The local storage is working properly but as soon as I refresh the items from the local storage get deleted.
const [notes, setNotes] = useState([]);
// This is the state variable that contains all the notes that are entered by the user.
useEffect(() => {
window.localStorage.setItem('react-notes-app-data', JSON.stringify(notes));
}, [notes]);
useEffect(() => {
const data = window.localStorage.getItem('react-notes-app-data');
if (data !== null) setNotes(JSON.parse(data));
}, []);
I have used these two useEffect() hooks. The first one adds the note entered by the user into the local storage, every time the notes state gets updated. I have given it a key of 'reacet-notes-app-data'.
The second useEffect() is supposed to render the notes from the local storage, the first time I render my page. So I check if the data is null or not. If it is not null I update the notes array with the elements already present in the local storage. But it does not show the already present items. Basically when I refresh the local storage gets refreshed too and gets empty.
When the page gets refreshed the initial state of notes set as an empty array []
Solution:
const savedNotes = JSON.parse(localStorage.getItem('react-notes-app-data'));
const [notes, setNotes] = useState(savedNotes || []);
Hope it works fine. If it still does not work then please share the code where you update the state notes.
Related
Looking for the best way to cache a users checkbox selections with material UI the browser/react. I would prefer to just use the browser and temporary storage as the options only need to persist if the user navigates away and comes back to the form in the same session. I do not need to save them on the user object as they do not need to persist through multiple sessions. Suggestion for the most optimal way to save a simple checkbox form selections? thanks!
So I found the best modern solution to use react hooks with local storage. To pull an item on load of the state component. Use the following guidelines
//Get Stored:
const [state, setName] = useState(() => {
// getting stored value
const saved = localStorage.getItem("name");
const initialValue = JSON.parse(saved);
return initialValue || "";
});
To set an item:
We can also use the useEffect React Hook to perform side effects, such as storing data in the browser storage. This makes this Hook a perfect place to call the setItem method.
Open the components/Form1.js file and add the following code above the return statement:
useEffect(() => {
// storing input name
localStorage.setItem("name", JSON.stringify(name));
}, [name]
Blog Post I followed: https://blog.logrocket.com/using-localstorage-react-hooks/
Here's the filter that I have set up so far. But I am having trouble finding a way to store the selected values. Should I be using local storage or session storage for what I am trying to achieve here?
const [filter, setFilter]= React.useState<AssignedFilterTypes>(AssignedFilterTypes.All);
const res = content.filter(c => c.percentage !== 100).sort((a, b) => compare(a, b, sort));
const storedFilter = sessionStorage.setItem('storedFilter',filter)
if(statistics && filter !== AssignedFilterTypes.All) {
return res.filter((c) => statistics[c.id].num_users);
}
return res;
}, [sort, showContent, filter, courses, programs, packages]);
Session storage gets cleared when the tab is closed. It persists when the page reloads, though. If you don't want to lose the data when the browser is closed, you need local storage. Note that if you are in a private window, it will clear after you close it.
I have a situation where I have some values in stored local storage. I want to clear those values when the page loads for the first time. But, after that, if I want to set those values again,I should be able to do this and page refresh shouldn't remove this as well. So. the question is: are there any ways of doing something only on initial loads of the component and don't do anything afterwards.
Yes, that is the typical use of sessionStorage. It works the same way as localStroage, but it will be clear after users closes browsers. However, between page reloads, it is preserved.
You can use it like this:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
const data = sessionStorage.getItem('key');
You can create a count variable and when react app runs for the first time useEffect will remove required items from localstorage and will set count to 1 in localstorage and then everytime component re-renders it will check in localstorage if count is 1 if it is 1 then it won't remove item from localstorage.
useEffect(() => {
if(localStorage.getItem('count') !== '1') {
localStorage.removeItem('val')
localStorage.setItem('count', '1')
}
set()
}, [])
const set = () => {
localStorage.setItem('val', 'skndkj')
}
I'm trying to implement an auto saving function with React and everything is working fine when i'm saving to local storage but my problem is when i for example close the window and try to retrieve the data i don't want to get them from the local storage but instead from the editorData function. I'm not really sure how to approach this problem.
const Editor = ({ data, setFieldValue, fieldProps, t }) => {
const editorName = fieldProps.name;
const [editorData, setEditorData] = useState(
element.setData(editorName, data)
);
const storageData = localStorage.getItem(`editorData`);
useEffect(() => {
setFieldValue(
editorName,
element.convertDataToFieldType(editorName, editorData)
);
setInterval(function() {
localStorage.setItem(`editorData`, JSON.stringify(editorData));
}, 20000);
}, [editorData]);
return (
<Pages
editorData={JSON.parse(storageData) || editorData}
setEditorData={setEditorData}
editorName={editorName}
setFieldValue={setFieldValue}
/>
);
};
On the Pages component inside the return i'm taking the local storage data and if not the editor data.
I'm not sure, that I understood your problem correctly, but i suggest, that you can use sessionStorage instead of localStorage.
It also allows you to store data in browser, but if you close tab or browser this data will be removed.
So you can use it, and every time you want to access your data you can simply check is there any data in your sessionStorage, if it is - just grab it, if no - use your function.
So If user will close the window, next time he'll open it - sessionStorage will be empty
I am trying to have my login page redirect to my main page.
I do this by using:
this.props.history.push("/userdashboard");
This works but on The main page there are const variables pulled in from Constants.js, which contains USER_ID, set from local storage:
let user_id = null;
try {
user_id =
window.localStorage.getItem("user_info") &&
JSON.parse(window.localStorage.getItem("user_info")).user_id;
} catch (err) {
console.error("Error Parsing user_info user_id");
}
const USER_ID = user_id;
export { USER_ID };
and then imported with
import { USER_ID} from "../constants/Constants";
The problem is that, these constants are still null and do not contain the new information until the page is reloaded.
I would like to be able to do this without using location.reload, as I want the user to be pushed into a specific page sometimes.
This is coming from my login page which waits for the action to finish then pushes
this.props.loginFunc(login_data).then(() => this.completeLogin());
completeLogin() {
this.props.history.push("/userdashboard");
}
I cannot figure out a way to refresh this const data. Also I am not entirely sure why these constants are used for getting the item from local storage every time, which is not expected, and is used in enough places that it would be a pain to refactor.
I'm not sure that const vs let (vs var, I guess) makes a difference, here. What is important that the localStorage is being read once. When is it supposed to be updated after the one initial reading? I don't see that piece of code.
Put this line
user_id = window.localStorage.getItem("user_info") && JSON.parse(window.localStorage.getItem("user_info")).user_id;
where the script should check for updates, if you expect updates at runtime.
The whole point of constants is that they cannot be reassigned. So each time the Constants.js is imported, it will always use the previous const value.
You've already got a let user_id variable, simply export that
let user_id = null
try {
user_id = window.localStorage.getItem("user_info") && JSON.parse(window.localStorage.getItem("user_info")).user_id
}
catch(err) {
console.error("Error Parsing user_info user_id")
}
export {
USER_ID: user_id,
}