Accessing vuex modules data from within a plugin - vue.js

I am moving some data from the vuex store into its own module. Most of it works great, but I'm running into an issue that I can't seem to fix.
I have a plugin that I add, and that plugin also needs access to the store.
So at the top of that plugin, we import the store:
import store from '../store/store';
great - further down that plugin, I'm accessing the data of the store in a method that I expose on the service:
hasPermission(permission) {
return (store.state.authorization.permissions.indexOf(permission) >= 0);
}
Please note authorization is now a seperate module, and is no longer part of the root state object.
now the funny thing is that the above will return an error telling me indexOf is not a function.
When I add the following, however:
hasPermission(permission) {
console.log('Validating permission ' + permission);
console.log(store.state);
return (store.state.authorization.permissions.indexOf(permission) >= 0);
}
I notice that (1) the output to console is what I expect it to be, and (2), I'm not getting the error, and my menu structure dynamically builds as expected...
so I'm a bit confused to say the least...
authorization.permissions is updated each time a user authenticates, logs out, or chooses another account to work on; in these cases we fetch updated permissions from the server and commit it to the store, so we can build our menu structure based on up-to-date permissions. Works pretty good, but I'm not sure I understand why this fails to be honest.
The plugin is created as follows in the install:
Vue.prototype.$security = new Vue(
...
methods: {
hasPermission: function(permission) {
...
}
}
...
);

Related

UserActions logic is moved to #spartacus/user

Based on this upgrade suggestion I’m trying to import UserActions/UserDetailsAction from #spartacus/user lib but am getting the error has no exported member.
// TODO:Spartacus - UserActions - Following actions 'ForgotPasswordEmailRequestAction', 'ResetPasswordAction', 'EmailActions', 'UpdatePasswordAction', 'UserDetailsAction' were removed. Logic was moved to '#spartacus/user'
Module ‘“#spartacus/user”’ has no exported member ‘UserActions’.
import { UserActions } from '#spartacus/user';
this.store.dispatch(new UserActions.LoadUserDetails(user));
import { UserActions } from '#spartacus/user';
Tried to import UserActions from the user lib
According to the technical changes documentation, you should use the new recommended approach with commands and queries as mentioned in the link. But you can also try importing from #spartacus/user/account, #spartacus/user/profile or #spartacus/core bearing in mind that your previously used actions may not exist anymore.
In case it helps, a similar question was also asked here.
Based on technical changes in Spartacus 4.0, Some branches of the ngrx state for the User feature were removed and logic has been moved to facades in #spartacus/user library.
In your case, instead of dispatching an action, simply use the get method from UserAccountFacade that is part of #spartacus/user.

Recommended dynamic runtime configuration technique on nuxtjs (other than dotenv)

I have been trying to use publicRuntimeConfig / privateRuntimeConfig
On nuxt 2.4.1, I have defined my runtime config as follows on nuxt.config.js
publicRuntimeConfig: {
DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL,
},
privateRuntimeConfig: {
AUTH_APP_CLIENT_SECRET: process.env.VUE_APP_AUTH_APP_CLIENT_SECRET,
},
and calling it as follows on my login.vue
asyncData( ctx ) {
console.log(ctx.$config.DATA_API_HOST_URL)
//some activity
}
The keys are showing up on $config inside asyncData. I debugged on chrome dev tools. But value is not read from process.env.VUE_APP_DATA_API_HOST_URL. The value is showing up as undefined. However, process.env.VUE_APP_DATA_API_HOST_URL is showing the value OK. The whole point is to move away from process.env.
this.$config.DATA_API_HOST_URL also does not access the values.
'${DATA_API_HOST_URL}' is shown in examples but I believe it is only for explicit param declarations at asyncData like asyncData( { $config : {DATA_API_HOST_URL}).
When I pass values as it is using DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL || 'https://test.api.com', it seems to copy the value fine using ctx.$config.DATA_API_HOST_URL!
Looking to me like copying process.env to *RuntimeConfig has a problem!
What is the recommended way of importing and using runtime configurations?
As per documentation in the Nuxt blog post you marked, the feature your are trying to use is released in 2.13 (you´re using 2.4 if i not misunderstood). That could be the reason behind the behaviour you're seeing.
I'd recommend update your project dependencies or trying another approach.
I think you should use Docker to set dynamic runtime config like link below:
https://dev.to/frontendfoxes/dockerise-your-nuxt-ssr-app-like-a-boss-a-true-vue-vixens-story-4mm6

How to run installation script only once in react-native

I have created a react native app.
For this app one simple database installation script should run for only one time.
It should happen when the app is installed.
Is there any better way to add a condition or any function that will run this installation code only once while installation.
Usually, databases have a special feature that called migrations. It`s helpful when you trying migrate your database schemas from one version to another. But also, you can use it like pre-fill script for your database on initial step.
Also, you can have a special script, that can pre-fill your database on initial step. But in this case, you should properly change implementation depend on each new your database scheme.
For achieve 2, you can have some variable in your database (or key-value storage like AsyncStorage) like pre-filled that indicate state of your database. When you start application check if this value is false and start database pre-filling, otherwise just use your already prepared data.
You should use useEffect to execute a piece of your code once.
Import it like this;
import React, { useEffect } from 'react'
Then u can use it to execute once or when a fuction is called;
useEffect(
async () => {
const allItems = await fetchSomeData()
setStatus({ loading: false, dataList: allItems})
},
[
//when leave this array empty this above script will execute once
],
)

How to add modernizr build so that I can properly check Modernizr.capture? (currently always undefined)

I need to check if the user's device can input from a camera on my site. To do this I am attempting to use modernizr. I have followed the steps/example code provided on their site but when I test the capture attribute, I always get undefined, regardless of if I am on a device that supports capture.
Steps I followed:
I browsed for the input[capture] attribute and added it to the build
I copied the demo code to check this feature and added it to my project
I downloaded the build, added the js file to my project, and included the appropriate reference in my page
However after all of this, when inspecting Modernizr.capture in the chrome inspector, it always shows up as undefined.
My basic check function is as follows:
$scope.hasCamera = function() {
if (Modernizr.capture) {
// supported
return true;
} else {
// not-supported
return false;
}
}
This is my first time using Modernizr. Am I missing a step or doing something incorrectly? I also installed modernizr using npm install and tried adding the reference to a json config file from the command line.
Alternatively, how might I check if my device has a camera?
Thank you very much for your time. Please let me know if I am being unclear or if you need any additional information from me.
A few things
while photos are helpful, actual code hosted in a public website (either your own project, or on something like jsbin.com) is 10x as useful. As a result, I am not sure why it is coming back as undefined.
The actual capture detect is quite simple. It all comes down to this
var capture = 'capture' in document.createElement('input')`
Your code is a lot more complicated than it needs to be. Lets break it down. You trying to set $scope.hasCamera to equal the result of Modernizr.capture, and you are using a function to check the value of Modernizr.capture, and if it is true, return true. If it is false, return false. There is a fair bit of duplicated logic, so we can break it down from the inside out.
Firstly, your testing for a true/false value, and then returning the same value. That means you could simplify the code by just returning the value of Modernizr.capture
$scope.hasCamera = function() {
return Modernizr.capture
}
While Modernizr will always be giving you a boolean value (when it is functioning - without seeing your actual code I can't say why it is coming back as undefined), if you are unsure of the value you can add !! before it to coerce it into a boolean. In your case, it would make undefined into false
$scope.hasCamera = function() {
return !!Modernizr.capture
}
At this point, you can see that we are setting up a function just to return a static value. That means we can just set assign that static value directly to the variable rather than setting up a function to do that
$scope.hasCamera = !!Modernizr.capture
Now, the final thing you may be able to do something better is if you are only using Modernizr for this one feature. Since it is such a simple feature detection, it is overkill to be using all of Modernizr.
$scope.hasCamera = 'capture' in document.createElement('input')`

App Folder files not visible after un-install / re-install

I noticed this in the debug environment where I have to do many re-installs in order to test persistent data storage, initial settings, etc... It may not be relevant in production, but I mention this anyway just to inform other developers.
Any files created by an app in its App Folder are not 'visible' to queries after manual un-install / re-install (from IDE, for instance). The same applies to the 'Encoded DriveID' - it is no longer valid.
It is probably 'by design' but it effectively creates 'orphans' in the app folder until manually cleaned by 'drive.google.com > Manage Apps > [yourapp] > Options > Delete hidden app data'. It also creates problem if an app relies on finding of files by metadata, title, ... since these seem to be gone. As I said, not a production problem, but it can create some frustration during development.
Can any of friendly Googlers confirm this? Is there any other way to get to these files after re-install?
Try this approach:
Use requestSync() in onConnected() as:
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Drive.DriveApi.requestSync(getGoogleApiClient()).setResultCallback(syncCallback);
}
Then, in its callback, query the contents of the drive using:
final private ResultCallback<Status> syncCallback = new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (!status.isSuccess()) {
showMessage("Problem while retrieving results");
return;
}
query = new Query.Builder()
.addFilter(Filters.and(Filters.eq(SearchableField.TITLE, "title"),
Filters.eq(SearchableField.TRASHED, false)))
.build();
Drive.DriveApi.query(getGoogleApiClient(), query)
.setResultCallback(metadataCallback);
}
};
Then, in its callback, if found, retrieve the file using:
final private ResultCallback<DriveApi.MetadataBufferResult> metadataCallback =
new ResultCallback<DriveApi.MetadataBufferResult>() {
#SuppressLint("SetTextI18n")
#Override
public void onResult(#NonNull DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while retrieving results");
return;
}
MetadataBuffer mdb = result.getMetadataBuffer();
for (Metadata md : mdb) {
Date createdDate = md.getCreatedDate();
DriveId driveId = md.getDriveId();
}
readFromDrive(driveId);
}
};
Job done!
Hope that helps!
It looks like Google Play services has a problem. (https://stackoverflow.com/a/26541831/2228408)
For testing, you can do it by clearing Google Play services data (Settings > Apps > Google Play services > Manage Space > Clear all data).
Or, at this time, you need to implement it by using Drive SDK v2.
I think you are correct that it is by design.
By inspection I have concluded that until an app places data in the AppFolder folder, Drive does not sync down to the device however much to try and hassle it. Therefore it is impossible to check for the existence of AppFolder placed by another device, or a prior implementation. I'd assume that this was to try and create a consistent clean install.
I can see that there are a couple of strategies to work around this:
1) Place dummy data on AppFolder and then sync and recheck.
2) Accept that in the first instance there is the possibility of duplicates, as you cannot access the existing file by definition you will create a new copy, and use custom metadata to come up with a scheme to differentiate like-named files and choose which one you want to keep (essentially implement your conflict merge strategy across the two different files).
I've done the second, I have an update number to compare data from different devices and decide which version I want so decide whether to upload, download or leave alone. As my data is an SQLite DB I also have some code to only sync once updates have settled down and I deliberately consider people updating two devices at once foolish and the results are consistent but undefined as to which will win.