Listening for change to property in ngrx - ngrx

In my first component I have set up a property like so:
linkEnabled: boolean = false;
and when this is set to false, certain routes will not be able to be accessed by users which I've set up in my html file like so:
<a class="nav-link" [routerLink]="linkEnabled ? ['/libraries']: null" [routerLinkActive]="linkEnabled ? 'active-route' : 'is-disabled'">
This is set to false until a project has been selected, this is done in another component
In the second component I've imported the first one like so:
import { NavSidebarComponent } from '../nav-sidebar/nav-sidebar.component';
and added it to the constructor:
constructor(private store: Store<AppState>,
..........
private navSidebarComponent: NavSidebarComponent
) { }
and in the ngOnit, where the project is set, I call the linkEnabled value and set to true for when project name is not null:
this.projectNameSub = this.store.pipe(select(ProjectSelectors.selectCurrentProjectName))
.subscribe(projectName => {
this.projectName = projectName;
if(this.projectName !=null) {
this.navSidebarComponent.linkEnabled = true;
}
});
The issue I am having, is that I am not sure how to get the first component to listen to the changes so that it know that linkEnabled has now been set to true? As at the moment it just sees it as false so I know I am missing a step but I'm just not sure what. Is there a way to subscribe to the value so that it can listen to it changing in the ngOnInit in the first component?
I had thought of creating a function like so within the first component:
public activateRoutes(): Observable<boolean> { console.log("activate routes called"); return of(this.linkEnabled = true); }
and then in the ngOnit do something like:
this.activateRoutes().subscribe((link) => { this.linkEnabled = link; })
and then in the ngOnit in the second component, instead of doing:
this.navSidebarComponent.linkEnabled = true;
I would do: this.navSidebarComponent.activateRoutes();
However all that is happening is that on page load, the linkEnabled is set to true and it's not working at all as I need it to

Solved this issue by creating new action, reducer and selectors file to store this in the store and could then do:
this.routeEnabledSub = this.store.pipe(select(RouteSelectors.selectRouteEnabled))
.subscribe(routeEnabled => {
this.routeEnabled = routeEnabled;
});
in the first component
and then in the second one, update it like so:
if(this.projectName !=null) {
this.store.dispatch(RouteActions.setRouteActive(
{ routeActive: true }));
} else {
this.store.dispatch(RouteActions.setRouteActive(
{ routeActive: false }));
and in html check for linkEnabled being set like so:
[routerLinkActive]="linkEnabled ? 'active-route' : 'is-disabled'"

Related

stenciljs: Issue with slot

I have created a simple web (stencil) component AuthGuard, not to be be confused with Angular's AuthGuard.
The purpose of this component is to check if the user is logged in.
If yes, render the slot html.
If not, render the Signup button.
The component code is as follows:
import { Component, Host, h } from '#stencil/core';
import { Build, State } from '#stencil/core';
import { AuthService } from 'auth/auth.service';
import { ConfigService } from 'common/config.service';
#Component({
tag : 'auth-guard',
styleUrl : 'auth-guard.css',
shadow : true,
})
export class AuthGuard {
#State() canRender : boolean = false;
componentWillLoad() {
if (Build.isBrowser) {
const timerId = setInterval(() => {
if (AuthService.isInitialized) {
AuthService.vol$.subscribe(_u => {
this.canRender= true;
});
clearInterval(timerId);
}
}, ConfigService.loadTime);
}
}
render() {
console.log('auth guard :: render', this.canRender, AuthService.me);
return (
<Host>
{
this.canRender ? (
AuthService.me && AuthService.me.id.length > 0 ? (
<slot></slot>
) : (
<ion-button
href="/signup"
routerDirection="forward"
color="danger">
Signup
</ion-button>
)
): null
}
</Host>
);
}
}
Now in the other file, I use the following code:
<auth-guard slot='end'>
<volunteer-mini volunteer={AuthService.me}></volunteer-mini>
</auth-guard>
With this what I am expecting is
Nothing to be rendered, till this.canRender becomes true.
Once this.canRender becomes true, If AuthService.me is valid, render the slot HTML,
If AuthService.me is null, render signup button.
But seems when this.canRender is false, it tried to render volunteer-mini the slot HTML, which is a problem. Since volunteer-mini internally depends on AuthService.me, which is not yet initialized.
But once this.canRender becomes true, other 2 scenarios are working fine.
It's in general a bad idea to write an auth-guard using stencil. The core problem is that your slot exists before your component has initialized.
Therefor, using your current code, you'd have to manually remove the slot after you decided that you don't have the rights.
Additionally, if you do not define a slot position, but still provide a slot-content in your parent, it will still be appended to your inner children.
To resolve this problem, you can refactor your component to an function, like <Host>, but this has other pits to consider.

Vue with binded aria-hidden

I want to show a modal with vue.
with aria-hidden="false" it should be visible.
I added this snippet with a v-bind :aria-hidden="modalHidden" to the div and set it to false by default (for testing purpose only):
created() {
this.modalHidden = false;
},
but this attribute is only in the DOM when it's != false.
is there any possibility to set this value to false?
You must use data to change bind value. For example:
:aria-hidden="[!isVisible]"
data() {
return {
isVisible: false
};
}
After that you can change value at any stage of the component:
// mounted
mounted() {
this.isVisible = true
},
// or event
methods: {
onClickEvent() {
this.isVisible = !this.isVisible
}
}
I hope this will help you.

ReactJS not setting class based on expression

I'm actually trying to toggle a class on an element when user clicked. But unfortunately, my code only set class for single element. It looks like the view is not refreshing for subsequent clicks, even the set class is not removing. But my store is properly updating.
Here is my code.
class MyInterests extends Component {
constructor(props) {
super(props);
this.state = {selected: []};
}
toggleChip(id, index, event){
const { interestChanged } = this.props;
let index = this.state.selected.indexOf(id);
if(index === -1){
this.state.selected.push(id);
}else{
this.state.selected.splice(index, 1);
}
interestChanged(this.state.selected);
}
render() {
const {classes, myinterests: { categories, userinterest } } = this.props;
const getClassNames = (id) => {
return classNames(classes.chip, {[classes.selected]: (userinterest.indexOf(id) !== -1)});
}
return (
/*..... Few element to support styles....*/
{categories.map((data, index) => {
return (
<Chip
key={data._id.$oid}
label={data.name}
onClick={this.toggleChip.bind(this, data._id.$oid, index)}
className={getClassNames(data._id.$oid)}
/>
);
})}
);
}
}
Can anyone tell me what is wrong in this or how can I achieve this?.
Since state is immutable, you cannot use .push on it.
By using this.state.selected.push(id) you're mutating the state thus not signaling react on the change making the change vulnerable to future state updates (remember that setState is asynchronous and changes are batched for single action).
Take a look at this for how to solve it.
In your case, a better way to update the state would be something like this:
// create a copy of the current array
var selected = this.state.selected.slice();
// push the new element to the copy
selected.push(id);
// replace the current array with the modified copy
this.setState({ selected: selected });

Make/ Create checkbox component in react native

I have been facing some issues with the native base checkbox and AsynStorage. In fact, AsynStorage only accepts strings by default BUT can store boolean variables also, I tried to use that method but I get a string stored every time.
While the checkbox does only accept boolean variables and throws a warning if I tried to use a string and it does not show the previous state of the checkbox (checked or not ).
So, I decided to make my own checkbox using TouchbleOpacity .. So do you guys have any idea how to make it ?
Here is the result i want to achieve:
So, the purpose is to make a checkbox settings page that controls the style of a text in another page and to get the checkbox as left the previous time, for an example : if I check it , I change the page and go back again to the settings page , I need to find it checked (indicating the previous state)
The code is
in the settings page :
toggleStatus() {
this.setState({
status: !this.state.status
});
AsyncStorage.setItem("myCheckbox",JSON.stringify(this.state.status));
}
// to get the previous status stored in the AsyncStorage
componentWillMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
this.setState({
status: value
});
if (this.state.status == "false") {
this.setState({
check: false
});
}
else if (this.state.status == "true") {
this.setState({
check: true
});
}
if (this.state.status == null) {
this.setState({
check: false
});
}
});
}
render {
return(
...
<CheckBox
onPress={() => { this.toggleStatus() }
checked={ this.state.check }/>
)}
In other page :
componentDidMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
JSON.parse(value)
this.setState({
status: value
});
});
}
This code change the status after TWO clicks and I don't know why and i get this weird output in the console, every time I click the checkbox
If you take a look at AsyncStorage documentation, you can see that, in fact, the method getItem() will always return a string (inside the promise).
For the problem with the AsyncStorage you should consider trying to parse this string returned to a boolean using this method explained here and then use this parsed value inside the native base checkbox.
But if you want to do your own component, try doing something like this:
export default class Checkbox extends Component {
constructor(){
super();
this.state = { checked: false }
}
render(){
return(
<TouchableOpacity
onPress={()=>{
this.setState({ checked : !this.state.checked });
}}
>
<Image source={this.state.checked ? require('checkedImagePath') : require('uncheckedImagePath')} />
</TouchableOpacity>
);
}
}
You will need to set some style to this image to configure it the way you want.
-- Based on your edition:
I can't see nothing wrong on your toggleStatus() method in settings page, but try changing your componentWillMount() to this:
componentWillMount(){
AsyncStorage.getItem('myCheckbox').then((value) => {
if (value != null){
this.setState({
check: (value == 'true')
});
}
});
}
However in the other page the line you do JSON.parse(value) is doing nothing, once you are not storing the result anywhere.

How to use aurelia-validate with a object properties to validate?

I'm using aurelia-validate and my validation works fine if I use variables, but I need it to validate properties of an object rather than a variable:
Here's what works:
import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import {ItemService} from './service';
export class EditItem {
static inject() {
return [Validation, ItemService];
}
#ensure(function(it){
it.isNotEmpty()
.hasLengthBetween(3,10);
})
name = '';
#ensure(function(it){
it.isNotEmpty()
.hasMinLength(10)
.matches(/^https?:\/\/.{3,}$/) //looks like a url
.matches(/^\S*$/); //no spaces
})
url = '';
constructor(validation, service) {
this.validation = validation.on(this);
this.service = service;
}
activate(params){
return this.service.getItem(params.id).then(res => {
console.log(res);
this.name = res.content.name; //populate
this.url = res.content.url;
});
}
update() {
this.validation.validate().then(
() => {
var data = {
name: this.name,
url: this.url
};
this.service.updateItem(data).then(res => {
this.message = "Thank you!";
})
}
);
}
}
Here's what I'm trying to do (but doesn't work)...also I'm not sure if it's better to keep the properties on the class or have a property called this.item which contains the properties (this is the typical angular way):
import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import {ItemService} from './service';
export class EditItem {
static inject() {
return [Validation, ItemService];
}
#ensure(function(it){
it.isNotEmpty()
.hasLengthBetween(3,10);
})
this.item.name; //no assignment here should happen
#ensure(function(it){
it.isNotEmpty()
.hasMinLength(10)
.matches(/^https?:\/\/.{3,}$/) //looks like a url
.matches(/^\S*$/); //no spaces
})
this.item.url; //no assignment?
constructor(validation, service) {
this.validation = validation.on(this);
this.service = service;
this.item = null;
}
activate(params){
return this.service.getItem(params.id).then(res => {
console.log(res);
this.item = res.content; //populate with object from api call
});
}
update() {
this.validation.validate().then(
() => {
var data = {
name: this.item.name,
url: this.item.url
};
this.service.updateItem(data).then(res => {
this.message = "Thank you!";
})
}
);
}
}
Can someone give me some guidance here on how to use a validator against an existing object (for an edit page)?
The validation works in all kinds of situations, but using the #ensure decorator can only be used to declare your rules on simple properties (like you found out).
Hence...
Option a: replace the ensure decorator with the fluent API 'ensure' method, this supports 'nested' or 'complex' binding paths such as:
import {Validation} from 'aurelia-validation';
import {ItemService} from './service';
export class EditItem {
static inject() {
return [Validation, ItemService];
}
constructor(validation, service) {
this.validation = validation.on(this)
.ensure('item.url')
.isNotEmpty()
.hasMinLength(10)
.matches(/^https?:\/\/.{3,}$/) //looks like a url
.matches(/^\S*$/)
.ensure('item.name')
.isNotEmpty()
.hasLengthBetween(3,10);
this.service = service;
this.item = null;
}
activate(params){
return this.service.getItem(params.id).then(res => {
console.log(res);
this.item = res.content; //populate with object from api call
});
}
update() {
this.validation.validate().then(
() => {
var data = {
name: this.item.name,
url: this.item.url
};
this.service.updateItem(data).then(res => {
this.message = "Thank you!";
})
}
);
}
}
Note: you can set up your validation even before item is set. Cool, no?
Option b: Since the validation rules are specific to the item, you could move your validation rules inside your item class using the #ensure decorator inside that class instead.
You can then set up validation in your VM after you've retrieved the item: this.validation = validation.on(this.item); or, your service can set up the validation when it returns your item to your VM and make it an intrinsic part of the model: item.validation = validation.on(item);
Option a is easiest and seems to match your experience. Option b is more maintainable, as the validation rules for your model will live on the model, not on the view-model. However if you go with option b, you might have to adjust your HTML a bit to make sure validation hints appear.
Use the .on method of the validator to apply your rules to object properties.
The example below is called after I retrieve an object named stock, it validates that the quantity is not empty and is numeric only. Hope this helps...
let stock = {
name: 'some name'
minimumQuantity: '1'
};
applyRules() {
ValidationRules
.ensure((m: EditStock) => m.minimumQuantity)
.displayName("Minimum Quantity")
.required()
.withMessage(`\${$displayName} cannot be blank.`)
.matches( /^[0-9]*$/)
.withMessage(`\${$displayName} must be numeric only.`)
.on(this.stock);
}

Resources