Issue
This Content is from Stack Overflow. Question asked by nihar saini
I am trying to store the button click logs user level so that I can use them somewhere in my project can you help me and tell how I can do that thing user level and set them using an api and get them when ever needed I am using svelte for my front end (store the log using firebase or something similar).user level means for each user different data will be saved and and I can use userid to get the details for the user by using userid
Solution
I suggest some decorator pattern applied to the event handler of interest.
Suppose you have a button and you want to log the on:click
event. You can decorate the handleClick
event handler with a decorator named monitor
.
<script>
import { getContext, onMount } from "svelte"
const monitor = getContext("monitor")
function handleClick(event) {
// do stuff
}
</script>
<button on:click={monitor(handleClick)}>Click me</button>
Now in your root <App />
component, you should initialize monitor
decorator and set it into context.
<script> // App.svelte
import { setContext } from "svelte"
import { Login } from "./components/Login.svelte"
let userId = null
const setUserId = (id) => { userId = id }
// the decorator wraps the original eventHandler
// and smuggles in some report logic
function monitor(eventHandler) {
return function decoratedEventHandler() {
// if we have the userId, we can start to report event logs
if (userId) {
const event = arguments[0]
// impl report as you needed
// it can simply be a HTTP POST to some backend API
// I definitely suggest add some throttle mechanism into it
report(userId, event)
}
eventHandler.apply(this, arguments)
}
}
setContext("monitor", monitor)
onMount(() => {
// if you store userId in cookie,
// you parse the cookie and restore it
userId = getUserIdFromCookie(document.cookie)
})
</script>
<!--
or maybe your Login component has some special logic
to get userId from backend
-->
<Login updateUserId={setUserId} ></Login>
This Question was asked in StackOverflow by nihar saini and Answered by hackape It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.