Vuex mutation: deconstruct state parameter using ES6 syntax (using quasar framework) - ecmascript-6

I have two different syntaxes. I can access my getters and my actions using mapGetters() and mapActions(). The first one doesn't deconstruct the state parameter and works. The second one does deconstruct the state but the mutation doesn't mutate the state while the getter can access the state and the action has no problem deconstructing the context.
I don't understand why.
Do I misuse ES6 / vuejs / vuex / quasar ?
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter1: 0,
counter2: 0
},
getters: {
counter1: state => state.counter1,
counter2: ({ counter2 }) => counter2
},
mutations: {
increment1: state => state.counter1++,
increment2: ({ counter2 }) => counter2++
},
actions: {
increment1: context => context.commit('increment1'),
increment2: ({ commit }) => commit('increment2')
}
})

A friend of mine gave me the answer. I misused ES6.
{ counter2 } doesn't reference state.counter2, but makes a copy of it.
It makes sense that I can't change state.counter2 when changing counter2.

Related

Implement conditional Routing in Angular

I am trying to implement the following functionality. When a button is clicked to check a condition, condition should be a variable (or a sum in my case) different from undefined (if different then success). Then either go to the success-page if the condition is met or to display the fail page if the condition is not met (+ if nothing was changed in the page just go to the success-page).
.html
<div class="d-flex justify-content-center">
<button type="button" (click)="updatePost()" routerLink="/success-page">Save</button>
The updatePost() method in the .ts file simply calls a function from the service and updates a user if some properties are changed (I have some input textboxes in the .html file).
updatePost() {
this.sharedservice.updateUser(this.user).subscribe(response => {
}, error => {
console.log(error);
})
}
I tried many ways but the functionality is not correct. The problem might be the order in which I tried to call the function and implement the logic.
Both pages are registered as routes.
const routes: Routes = [
{path: 'success-page', component: DisplaySuccessComponent},
{path: 'fail-page', component: DisplayFailPageComponent},
];
For that you should use Router from constructor. For that you need to provide constructor(private router: Router) {} then you need to check variable should not be undefined, null or not expected condition, then you need to route like
this.router.navigate(['fail-page']); and if not undefined, not null and as expected condition then you can navigate by using this.router.navigate(['success-page']);. So, your final code like below:-
// In HTML:-
<button type="button" (click)="updatePost()">Save</button>
// In ts:-
updatePost() {
this.sharedservice.updateUser(this.user).subscribe(response => {
this.router.navigate(['success-page']);
}, error => {
this.router.navigate(['fail-page']);
console.log(error);
})
}
you should not use routerLink in this case but navigate inside the upadtePost()function i.e:
updatePost() {
this.sharedservice.updateUser(this.user).subscribe(
response => {
this.router.navigate('/success-page');
},
error => {
console.log(error);
this.router.navigate('/fail-page');
});
}

Get json data in VueJS

onMounted(() => {
productService.value
.getProducts()
.then((data) => (products.value = data));
console.log((products))
});
When I print products with console.log, here what I have.
capture of the console
I see that the data I want are in RawValue but I don't know how to access them.
I tried Object.values(products) or just console.log(products._rawValue) or console.log(products.rawValue) it print undefined.
Do you know what function call ?
Thanks
There are 2 issues
#1 - you're using console.log(products) which shows you the reactive object, what you need instead is console.log(products.value) which will only show the value, which should match the content of data.produtcs
#2 - you might find that 👆 now shows an empty result. The reason that's happening is that you're calling the console log after the async function, but before it finishes, so you're calling it before it has a chance to update. To fix that, you can log as part of the async function
onMounted(() => {
productService.value
.getProducts()
.then((data) => {
products.value = data;
console.log(products.value);
})
});
If you're using the products inside a template, you don't need to worry about what's before or after the async function since it will re-render the component on change.
Also, you probably don't need to define productService as a ref, the class is likely not something that needs to be reactive, so you can just do simple assignment and then skip the .value to call getProducts
with axios what I do is take out the data with response.data you could try
onMounted(() => {
productService.value.getProducts().then((response) => (
products = response.data
));
console.log(products.length);
});

React Native - make dummy db get real data from api

I am quite new to React Native and JS and have recently purchased a React Native template which has a Dummy DB.
Ideally Id like it to pull data from an external JSON (api) which is being generated from a PHP website we already have running.
Here is the Dummy data file:
import {
DoctorModel,
TreatmentModel,
CampaignModel,
EventModel
} from "../models";
export const doctorsList: DoctorModel[] = [ { ##JSON HERE## } ];
export const treatmentsList: TreatmentModel[] = [ { ##JSON HERE## } ];
export const campaignList: CampaignModel[] = [ { ##JSON HERE## } ];
export const eventList: EventModel[] = [ { ##JSON HERE## } ];
I want it to export as the same values as above so it will work seamlessly with the current app configuration.
I have tried the following...
export const doctorsList: DoctorModel[] = () =>
fetch(' ##LINK TO API## ')
.then((response) => response.json());
But got this error:
Type '() => Promise<any>' is missing the following properties from type 'DoctorModel[]': pop, push, concat, join, and 27 more.
I have looked all over here and other platforms for a solution but cant find anything.
Again the ideal outcome would for it to work exactly how it would if I manually typed the JSON in as seen in the first code snippet.
Any help is much appreciated, still trying to wrap my head around React! :)
This doesn’t look like a react problem, but a typescript one. Typescript does a type inference from your return value to check and see if it matches what you’ve stated.
In short: you’ve just declared your types wrong.
The function doesn’t return a DoctorModel[] it’s returning Promise<DoctorModel[]>
export const doctorsList: Promise<DoctorModel[]> = () =>
fetch(' ##LINK TO API## ')
.then((response) => response.json() as DoctorsModel[]);
So changing that line ought to make your typescript compiler chooch again!

Object destructuring default using other destructured values

The follow works in node v8.11.4 and in babel transpiled JavaScript running on chrome
const myFunc = ({
aryOfObjs,
combinedObj = Object.assign({}, ...aryOfObjs),
}) => console.log(combinedObj);
myFunc({
aryOfObjs: [
{ foo: 'bar'},
{ biz: 'baz' },
]
}); // => { foo: 'bar', biz: 'baz' }
In EMACScript 2015 is this guaranteed to work as shown above?
I know node and babel aren't 100% EMACScript 2015 complaint but I believe they both implement the object destructuring spec I can't find anything explicit on mdn that says this is supported nor on the official ECMAScript 2015 spec
Yes, this is valid ES2015 code. aryOfObjs is a variable introduced into the function scope, and Object.assign({}, ...aryOfObjs) is an expression evaluated in that scope so it can access any of those variables. The only time this would be an error is if they were accessed out of order, like
const myFunc = ({
combindedObj = Object.assign({}, ...aryOfObjs),
aryOfObjs,
}) => console.log(combindedObj);
which would throw an error because aryOfObjs has not been initialized yet.

ES Lint rule for chained then promise calls

I am searching for an ES Lint rule that will force the following behavior:
aPromiseCall()
.then(() => {
// logic
})
.then(() => {
// logic
})
.catch(() => {
})
Notice that each .then should be indented by 4 spaces and on a . separate line
Use the following rule:
"indent": ["error", 4, { "MemberExpression": 1 }]
"MemberExpression" (default: 1) enforces indentation level for multi-line property chains. This can also be set to "off" to disable checking for MemberExpression indentation.
https://eslint.org/docs/rules/indent#memberexpression