K
K
keksum6662021-07-21 14:06:08
API
keksum666, 2021-07-21 14:06:08

How to get the settings right?

The task is this:
I get the settings from api (consists of a key and value), then I save it in a cookie (an alternative to hashing, I save it for 5 minutes), I created an action in vuex with settings loaded

async initOptions() {
      if (!Cookies.get('options')) {
        await Option.$query().get().then(response => {
          Cookies.set('options', JSON.stringify(response.map(function (item) {
            return [item.$attributes.option_key, item.$attributes.option_value]
          })), {expires: 1/24/60*5});
        })
      }
    }

After that, I made a getter in the form of a function that returns a value by key, if the key is not found, it returns the default value:
getOptionByKey: () => (key, def) => {
      return (new Map(JSON.parse(Cookies.get('options'))).get(key) ?? def);
    }

The problem is that the cookie expires after 5 minutes and needs to be loaded again, how can this be done correctly? (doing through the action that the getter returns is not an option, it’s not convenient to get the settings, it’s also not an option to call the action in the getter. For the first time I load the settings in App.vue, then they should be loaded if there are no cookies

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-07-21
@Kozack Vue.js

Why is Vuex here? Make a normal function that would take data from cookies or load via api. More or less like this:

async function getOption(key, def) {
  let options = Cookies.get('options')
  if (!options) {
   options = await Option.$query().get()
   Cookies.set('options', options)
  }

  return new Map(JSON.parse(options)).get(key) ?? def
}

Then just import and use this function in the required components

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question