How to get data from rxjs? - react-native

I have a file to save the random id to AsyncStorage.
AppService.js
import Rx from 'rxjs/Rx';
import uuid from 'uuid/v4'
import StorageService from '../storage/StorageService'
export default class AppService {
constructor() {
this.deviceuuid = null
}
rxInit() {
return StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
if (deviceuuid == null) {
this.deviceuuid = uuid()
console.log('deviceuuid is empty, create one')
return StorageService.shared.set('deviceuuid', this.deviceuuid)
} else {
this.deviceuuid = deviceuuid
return Rx.Observable.of(this.deviceuuid)
}
}).do((deviceuuid) => {
console.log(`deviceuuid is ${deviceuuid}`)
})
}
}
AppService.shared = new AppService()
StorageService.js
import Rx from 'rxjs/Rx'
import { AsyncStorage } from 'react-native'
import Storage from 'react-native-storage'
let storage = new Storage({
size: 1000,
storageBackend: AsyncStorage,
defaultExpires: null,
})
export default class StorageService {
set(key, value) {
return Rx.Observable.fromPromise(storage.save({key: key, data: value})).map(() => value)
}
get(key) {
return Rx.Observable.fromPromise(storage.load({key: key})).catch(() => Rx.Observable.of(null))
}
remove(key) {
return Rx.Observable.fromPromise(storage.remove({key: key})).catch(() => Rx.Observable.of(null))
}
}
StorageService.shared = new StorageService()
When I build the project I can see deviceuuid is 14c629ee-0dc7-43ef-91c2-eed642271670
Now I want to get the deviceuuid from another screen.
componentWillMount() {
console.log('LoginScreen componentWillMount');
console.log('rxInit data =>', AppService.shared.rxInit())
let testId = StorageService.shared.get('deviceuuid')
console.log('testID', testId);
StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
console.log('deviceuuid', deviceuuid);
this.setState({ uuid: deviceuuid })
}).do((deviceuuid) => {
console.log(`LoginScreen deviceuuid is ${deviceuuid}`)
})
}
the result like the image
I have no idea how to get deviceuuid.
and the code is not working. I can't see any console log result.
StorageService.shared.get('deviceuuid').flatMap((deviceuuid) => {
console.log('deviceuuid', deviceuuid);
this.setState({ uuid: deviceuuid })
}).do((deviceuuid) => {
console.log(`LoginScreen deviceuuid is ${deviceuuid}`)
})
I'm not familiar with rxjs, any help would be appreciated.

Related

To-dos don't update when I choose a to-do list

I have two components: TodoList and TodoListsList. They get their data from states in todos.js and todoLists.js modules accordingly. When I choose some to-do list, i.e mark it as active, TodoListsList is updated, but TodoLists isn't, thought the data is updated. Here's how I do it.
todoListsState and markAsActive() (todoLists.js):
import todos from '#/modules/todos.js'
// ... some code ...
const todoListsState = reactive({
todoLists: [],
todoListsAreLoading: false,
removedTodoListId: null,
editedTodoListId: null,
editedTodoListName: '',
baseTodoListsApiUrl: process.env.VUE_APP_BASE_TODO_LISTS_API_URL,
todoListCreationFormModalId: 'todoListCreationFormModal',
todoListNameChangeFormModalId: 'todoListNameChangeFormModal'
});
// ... some code ...
function markAsActive(value) {
let { close } = infoToast();
if (value) {
axios.post((todoListsState.baseTodoListsApiUrl + 'mark-as-active'), {
activatedTodoListId: value
}).then(function () {
getTodoLists();
const { getTodos } = todos();
getTodos();
}).catch(function () {
dangerToast('Failed to mark to-do list as active.');
}).finally(() => {
close();
});
}
}
todosState and getTodos() (todos.js):
const todosState = reactive({
todos: [],
activeTodoListId: 0,
removedTodoId: null,
editedTodoId: null,
editedTodoText: '',
todosAreLoading: false,
baseTodosApiUrl: process.env.VUE_APP_BASE_TODOS_API_URL,
todoAdditionFormModalId: 'todoAdditionFormModal',
todoEditFormModalId: 'todoEditFormModal'
});
// ... some code ...
async function getTodos() {
try {
todosState.todosAreLoading = true;
const response = await axios.get(todosState.baseTodosApiUrl);
todosState.activeTodoListId = response.data[0];
todosState.todos = response.data[1];
} catch (e) {
dangerToast('To-dos loading failed.');
} finally {
todosState.todosAreLoading = false;
}
}
How does todosState.todos look in console:
todosState.todos when Todos.vue is mounted:
It doesn't look like the array looses it's reactivity.
If you need something else to understand my question, feel free to ask. Help appreciated.
The problem is solved! I have just moved todosState out of
export default function () {}
and it works! Finally! This thread helped me a lot.

Delete item from pinia state

I am new to vue and I have just started using pinia. I wanna delete an item from array but it does not work
here is my store
import {defineStore} from 'pinia'
export interface ObjectDto {
input: string,
}
interface ObjectDtoInterface {
objects: Array<ObjectDto>
}
export const useSearchHistoryStore = defineStore('objectsStore', {
state: (): ObjectDtoInterface => {
return {
objects: [] as ObjectDto[]
}
},
actions: {
add(dto: ObjectDto) {
if (this.objects
.filter(shd => dto.input === shd.input)
.length === 0) {
this.objects.unshift(dto)
}
},
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
}
})
and here is the function from different .ts file
function delete(obj: ObjectDto) {
objectsStore.delete(obj)
}
add action works perfect, it adds item to the state but when I try to delete an item, nothing happens. The data I pass to delete method is 100% good because I checked this many times
Filter does not mutate the original object, you need to reasing
delete(obj: ObjectDto) {
this.objects = this.objects.filter(e => !(e.input === obj.input))
}
more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

click event in custom plugin ckeditor5

I have a custom plugin in ckeditor5.
When user click on toolbar icon my plugin convert selected test to custom element with a custom attribute name comment-id.
this work properly.
Now I want to watch on click element and get comment-id on click and I don't know how can I do that.
this is the code of my custom plugin
import uploadIcon from './message.svg'
import ButtonView from '#ckeditor/ckeditor5-ui/src/button/buttonview'
import Plugin from '#ckeditor/ckeditor5-core/src/plugin'
import Command from '#ckeditor/ckeditor5-core/src/command'
import './comment.css'
export default class CustomFileExporerPlugin extends Plugin {
init() {
const editor = this.editor
const config = editor.config.get('comment')
console.log(editor.editing.view.document.isFocused)
editor.editing.view.document.on('click', a => {
console.log(a)
})
editor.model.schema.extend('$text', { allowAttributes: 'comment' })
editor.conversion.attributeToElement({
model: 'comment',
view: (commentId, writer) => {
debugger
if (writer) {
return writer.writer.createAttributeElement(
'comment',
{
'comment-id': commentId,
class: `ck-comment-marker`
},
{ priority: 5 }
)
}
}
})
editor.commands.add('comment', new CommentCommand(editor))
editor.ui.componentFactory.add('comment', locale => {
const view = new ButtonView(locale)
view.set({
label: 'add comment',
icon: uploadIcon,
tooltip: true
})
view.on('execute', async () => {
editor.editing.view.focus()
let id = await config.callback()
editor.execute('comment', { value: 'comment', id })
})
return view
})
}
}
class CommentCommand extends Command {
refresh() {
const model = this.editor.model
const doc = model.document
this.value = doc.selection.getAttribute('comment')
this.isEnabled = model.schema.checkAttributeInSelection(
doc.selection,
'comment'
)
}
execute(options = {}) {
const model = this.editor.model
const document = model.document
const selection = document.selection
const highlighter = options.value
model.change(writer => {
const ranges = model.schema.getValidRanges(
selection.getRanges(),
'comment'
)
if (selection.isCollapsed) {
const position = selection.getFirstPosition()
if (selection.hasAttribute('comment')) {
const isSameHighlight = value => {
return (
value.item.hasAttribute('comment') &&
value.item.getAttribute('comment') === this.value
)
}
const highlightStart = position.getLastMatchingPosition(
isSameHighlight,
{ direction: 'backward' }
)
const highlightEnd = position.getLastMatchingPosition(isSameHighlight)
const highlightRange = writer.createRange(
highlightStart,
highlightEnd
)
writer.removeAttribute('comment', highlightRange)
writer.removeSelectionAttribute('comment')
} else if (highlighter) {
writer.setSelectionAttribute('comment', highlighter)
}
} else {
for (const range of ranges) {
writer.setAttribute('comment', options, range)
}
}
})
}
}
When rendering editor, you can catch custom plugin click event using below code.
const command = editor.commands.get('comment')
command.on('execute', () => { catch click event in custom plugin})

How can I pass information obtained from one apirest to another component using vuejs?

I'm in trouble I'm trying to pass information that gets from an api rest that's in a component A and store it in a variable of a B component
i've dealt with this:
Componente A:
data: () => {
return {
server: []
};
}
axios
.post("http://0.tcp.ngrok.io:13601//accountmanagement/login", LogInUser)
.then(res => {
this._UserLogin = res.data;
if (
this._UserLogin.credencial.rol.id_rol == 1 &&
this._UserLogin.credencial.correo == LogInUser.correo
) {
this.$router.push("admin");
} else if (
this._UserLogin.credencial.rol.id_rol == 2 &&
this._UserLogin.credencial.correo == LogInUser.correo
) {
this.$router.push("usuario");
this.server = this._UserLogin
//here I try to send the already verified user to another
component clear the request returns me a json if correct if
the registration is correct:
EventBus.$emit('serverSelected', this.server);
}
})
.catch(resError => {
alert(
"El servidor es en mantenimiento por favor intente mas tarde" +
resError
);
});
Component B:
data: () => {
return {
server: []
};
}
created() {
EventBus.$on(
"serverSelected",
function(serve) {
this.server = serve;
console.log("The person is: ", this.server);
}.bind(this)
);
}
including this does not show me any error or print me the information of the record that I try to send by eventBus.emit
Call eventBus:
import eventBus from '../../evenbus'
evenbus content:
import Vue from 'vue';
export const EventBus = new Vue();

NavigationStateUtils not pushing (using NavigationExperimental)

Here's my AppState class:
export default class AppState {
constructor() {
this.navigationState = {
index: 0,
routes: [{ key: "InitialView" }]
};
}
updateNavigationState(type, route = null) {
switch (type) {
case NavigationStateUpdateType.Push:
console.log(this.navigationState.routes.length);
console.log(this.navigationState.routes[0].key);
if (route !== null) {
console.log("Route: " + route);
this.navigationState = NavigationStateUtils.push(this.navigationState, { key: route });
}
case NavigationStateUpdateType.Pop:
this.navigationState = NavigationStateUtils.pop(this.navigationState);
}
}
}
Now if I do this inside InitialView:
this.props.appState.updateNavigationState(NavigationStateUpdateType.Push, "InitialView1");
Nothing happens. It seems like NavigationStateUtil.pushdoesn't work. Here's what the Console looks like:
AppState.js:18 1
AppState.js:19 InitialView
AppState.js:21 Route: InitialView1
AppState.js:18 1
AppState.js:19 InitialView
AppState.js:21 Route: InitialView1
AppState.js:18 1
AppState.js:19 InitialView
AppState.js:21 Route: InitialView1
Why isn't routes being updated? Or am I doing something wrong?
EDIT
My GlobalNavigation component (as asked):
const { CardStack: NavigationCardStack } = NavigationExperimental;
let GlobalNavigation = class GlobalNavigation extends Component {
render() {
return (React.createElement(NavigationCardStack, {renderScene: this._renderScene.bind(this), navigationState: this.props.appState.navigationState}));
}
_renderScene() {
return (React.createElement(InitialView, {appState: this.props.appState}));
}
};
By the way: all this code is generated by TypeSript.