Remember checked options for user on form. Material UI/React - javascript

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/

Related

How to save user search input when going to a new page?

let navigate = useNavigate();
const routeChange = () =>{
let path = `/ProductsNew`;
navigate(path);
}
const wrapperFunction = () => {
routeChange();
props.onSubmit(innerSearch)
}
I have an API full of data that I fill in my ag-grid-react table. But when I press search and go to the new page, the search gets wiped which I know why, I just can't seem to save the search value.
Well, there are plenty of options to store data, everything from creating Component wrappers using context, using storage in form of a cookie to using the local storage API or more perhaps commonly used for searches using post and gets variables.
Since post data is for server-side it won't be available for you using react. But as far as get goes in js you can use URLSearchParams or if you happen to use ReactRouter as it seems you can use useSearchParams.
You can find examples for all of the provided functions at the address I've linked them to. Good luck,

Local Storage gets refreshed when I refresh the page

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.

How to remove local storage value only on initial loads of the component

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')
}

Implement auto saving with local storage on a custom text field with React

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

Send Info after browserHistory.goBack

I'm building an App with reactjs and in some point I have a SearchForm, then I click on one of the items and in that view I have a back button.
What I want is to populate the search form with the previous data. I already achieved it with localStorage from javascript. And saving the state on componentWillUnmount, the problem is this data is always loaded even if I don't arrive from the go back.
Is there a way to add a kind of state to the goBack to tell it?
So, the best way here is to not use localStorage, and instead use history state.
When the user updates the form, you can do this (optionally debounce it for better performance):
history.replaceState(this.props.location.pathname, {
formData: JSON.stringify(formData),
});
Then when the component loads, you can access that state like this:
const {location} = this.props;
const routeState = location.state && location.state.formData;
if (routeState) {
this.setState({
data: JSON.parse(routeState),
});
}
If they refresh the page, or go to another page and go back, or go back and then go forward, they'll have that state. If they open it in a new tab, they won't have the state. This is usually the flow you want.

Categories

Resources