how to pass data consistently from page to page in Vue Js? - javascript

Currently I want to pass data from edit page to add page. So i pass the query using {path: '/test/admin/clinicvisit/add', query:{id:this.$route.params.id}}. I was able to pass the data to add page using the query however sometimes the data may not present when it refreshes a few times. Is there any possible way to make the data consistent stay in the add page ?
add.vue
async testRoute(){
let visitId = this.$route.query.id
if (visitId){
let clinicVisit = await this.api.medical.viewClinicVisit(visitId)
this.inputs = await this.api.medical.optionsClinicVisit()
this.$set(this.inputs.staff, "item_text", "username")
this.$set(this.inputs.staff, "item_value", "id")
this.$set(this.inputs.staff, "items", await this.api.profile.listStaff({}))
if(clinicVisit.staff){
this.$set(this.inputs.staff, "value", clinicVisit.staff)
this.$set(this.inputs.staff, "tmp_value", clinicVisit.staff_detail.name)
}
mounted()
{
this.testRoute()
}

This can be done in multiple ways.
Using a global store, You can use a library like Vuex to share the state between the components.
Using the Local Storage, if you want to preserve the data and keep saved after hard refreshing the page.
Using Session Storage, if you want to preserve the data and keep saved during the user session, but whenever the user close the browser tab it will be gone.

When you observe that the data is not present after a few refreshes, does it dissapear from the URL in your browser, or does it just not load?
If you want the data to stay more consistently, consider using localStorage
localStorage.setItem('item_text', 'username') //Save variable in browser data
let item_text = window.localStorage.getItem('item_text') //Get variable from browser data
EDIT:
If the URL is still present in the browser window, that sounds like a weird loading bug, where your code runs before the route is parsed by Vue.
You can try using a watcher instead of the "mounted" function:
watch: {
$route: {
immediate: true,
handler() {
this.testRoute()
}
}
}

I solved this error by setting a timeout function in my edit.vue.
handleCreate(event){
event.preventDefault();
this.$router.push({path: '/medical/admin/clinicvisit/add', query:{id:this.$route.params.id}},2000)
// now 'this' is referencing the Vue object and not the 'setTimeout' scope
this.loadClinicVisitData = true;
setTimeout(() => this.loadClinicVisitData = false,1000)
}

Related

Is there any way to cache the API response in VueJS

In our VueJS application, we are having few API's which are calling each and every time whenever the page reloads. In those API's. few response will never change and very few will rarely change. I planning to cache those API calls response and store it in a variable and use it whenever needed and reduce the number of requests when page reloads.
I am new to vueJS and not having any idea how to implement it. Is there anyway to achieve this in VueJS or Javascript? Any help would be most appreciated.
Sample HTML code,
<div class="col-sm-6">
<span>Is User Available? {{userInfo[is_user_available]}} </span>
<span> User Type : {{userType}} </span>
</div>
API call will be like below,
created: function () {
this.checkForUser();
},
methods: {
checkForUser: function() {
this.api.call('user_info', { username : this.username })
.then((response) => {
if (response) {
this.userInfo = response;
this.userType = this.userInfo['user_type'];
}
})
.catch((error) => {
this.userInfo.length = 0;
})
}
}
If you store the data in a regular Vuex store you will loose it on page refresh unless you use vuex-persistedstate plugin, which saves the store data on the local storage. (here is a working example)
Elaborating on #Mysterywood answer you can simply store it on local storage by yourself.
You can achieve that by simply doing
get:
const userType = window.localStorage.getItem('userInfo')
set:
window.localStorage.setItem('userInfo', response)
and remove:
window.localStorage.removeItem('userInfo')
There are few ways of doing this depending on how deep you want to go:
If you just want state to persists during the SPA session, you can do so:
Vuex if you would like to store globally accessible state/data. This allows your state to persist regardless of whether the components are destroyed/created.
Store it on your root-level Vue instance. If you're using the Vue CLI, this will be in your main.js. You can do something like so:
new Vue({
// ...
data: {
userType: {}
}
})
You can then access it via this.$root.userType. This is fine for small projects, but generally not recommended as things can get messy very quickly.
There's also EventBus, but again, this can get messy very quickly. EventBus is also deprecated in Vue3.
If you want to cache the response and access them again even after the user close their tab/browser, you will want to look into:
Cookies
localStorage
ServiceWorkers
check this, it can help :client-side storage in vuejs
Client-side storage is an excellent way to quickly add performance gains to an application. By storing data on the browser itself, you can skip fetching information from the server every time the user needs it. While especially useful when offline, even online users will benefit from using data locally versus a remote server. Client-side storage can be done with cookies, Local Storage (technically “Web Storage”), IndexedDB, and WebSQL (a deprecated method that should not be used in new projects).

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

Updating a web page to reflect deleted data from CRUD app without hard refresh

I have a to-do app that functions - I can create an item, check off that it's been completed, and delete the item using an X button next to it. When I create an item, it pops up immediately on the list. But when I delete an item, I have to manually refresh the page for it to update. What am I missing that would get it to update in real time?
index.html:
const deletebtns = document.getElementsByClassName('deletebutton');
for (let i = 0; i < deletebtns.length; i++) {
const deletebutton = deletebtns[i];
deletebutton.onclick = function(e) {
const todoId = e.target.dataset['id'];
fetch('/todos/' + todoId, {
method: 'DELETE',
});
}
}
app.py:
#app.route('/todos/<todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
try:
Todo.query.filter_by(id=todo_id).delete()
db.session.commit()
except:
db.session.rollback()
finally:
db.session.close()
return jsonify({ 'success': True })
location.reload ();
Should do it.
If you call this method from anywhere in the web page, the web page will reload. This reload will occur through the web cache. What is a cache exactly? It’s a temporary space your browser reserves to store documents, images and other data that it retrieves from a server. Caching of data allows a browser to speed up your browsing and lets you reload often-visited sites faster.
You can change the default cache reload by setting a forceGet parameter. This will cause the browser to reload the webpage by fetching the data from the server anew instead of using the cache. This can be accomplished by using the following code:
location.reload(true);
By default, the value of the forceGet parameter is false. This means that the location.reload method always looks like this:
location.reload(false)

I was wondering if someone could teach me how to use cookies in my code

I'm trying to make a "Window.alert game" in a browser window for fun, but I can't figure out how to use cookies to save player data if they mess up or close the window. Can someone help me?
LocalStorage is indeed your best option for saving data semi-permanently. One thing to remember is that localStorage only supports strings, so if you need to store more complex objects, you should JSON.stringify them (and JSON.parse the result when loading data).
A simple pattern is to use a single object to store your state, and to save this state to localStorage whenever a change is made to it (so that your latest data is always persisted). You can also listen to the window.beforeUnload method to save your state right before the window closes, but this may not always work (eg: if your browser or tab closes unexpectedly).
Here is an example of what you can do:
// saves your state to localStorage
function save(state) {
localStorage.setItem('state', JSON.stringify(state));
}
// execute code when the document is loaded
document.addEventListener('DOMContentLoaded', function () {
// load your state from localStorage if it has been previously saved
// otherwise, set the state to an empty object
var state = JSON.parse(localStorage.getItem('state')) || {};
// show your name if previously saved
// otherwise, prompt for a name and save it
if (state.name) {
alert('Your name is: ' + state.name);
} else {
state.name = prompt('What is your name?');
save(state);
}
});
To clear localStorage, you can call localStorage.clear().

What are my options when it comes to saving and reloading data with Quill.js?

I am making a note taking app and it is in the early prototyping stages, so I just want to hack together something that will work for myself.
My text editor is built using Quill, and I'm using Vue to structure the whole application. Currently, I don't have a back end, so no server.js.
I would like my application to be able to save the information that I put in the editor, and reload the information whenever I rebuild the app.
I checked out the autosave option provided by Quill here
But I'm not sure what to do with $.post and where to post it.
Can I simply post it to a local .json file?
What is the best thing to save in my case? The example was logging changes, what am I supposed to do with changes?
I apologize beforehand for the lack of clarity in my question, as I don't know exactly what I should be asking to achieve what I want.
Any advice is appreciated.
So if I understood correctly, what you're asking is how to implement quilljs' auto save feature when you have no server. But, you've already answered your own questions.
A simple way to do it would be saving the document into a local json file. But I don't know if you can do that using js.
Another way of doing it, is to save the content to the browser's local storage and loading the data every time you load the app.
var Delta = Quill.import('delta');
var quill = new Quill('#editor-container', {
modules: {
toolbar: true
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
// Store accumulated changes
var change = new Delta();
quill.on('text-change', function(delta) {
change = change.compose(delta);
});
// Save periodically
setInterval(function() {
if (change.length() > 0) {
console.log('Saving changes', change);
// Save the entire updated text to localStorage
const data = JSON.stringify(quill.getContents())
localStorage.setItem('storedText', data);
change = new Delta();
}
}, 5*1000);
// Check for unsaved data
window.onbeforeunload = function() {
if (change.length() > 0) {
return 'There are unsaved changes. Are you sure you want to leave?';
}
}
Then inside your vue component's mounted(), use the following to fetch the saved data:
const data = JSON.parse(localStorage.getItem('storedText'));

Categories

Resources