Adding computed decorator causes a TypeError - babeljs

I can't use #computed. If I run my code bellow I get an error:
Uncaught TypeError: An element descriptor's .kind property must be either "method" or "field", but a decorator created an element descriptor with .kind "undefined"
at _toElementDescriptor (app.js:46281)
at _toElementFinisherExtras (app.js:46283)
at _decorateElement (app.js:46273)
at app.js:46269
at Array.forEach (<anonymous>)
at _decorateClass (app.js:46269)
at _decorate (app.js:46251)
at Module../src/App/stores/UserStore.js (app.js:46301)
at __webpack_require__ (bootstrap:19)
at Module../src/App/stores/index.js (index.js:1)
And here is my UserStore.js file:
import {
configure,
runInAction,
observable,
action,
computed
} from 'mobx'
import API from '../api'
configure({ enforceActions: 'observed' })
class UserStore {
#observable users
#observable state
#observable currPage
#observable hasMore
#observable errors
constructor() {
this.users = []
this.state = 'loading'
this.currPage = 0
this.hasMore = true
this.errors = []
}
#action
addUser = (user) => {
this.users.shift(user)
}
#action
addUsers = (users) => {
this.users = this.users.concat(users)
}
#action
async fetchUsers () {
let req;
try {
req = await API.allUsers()
runInAction(() => {
this.state = 'done'
this.addUsers(req.body.users || [])
this.hasMore = (req.body.users && req.body.users.length) ? true : false
this.currPage = this.currPage + 1
})
} catch (e) {
runInAction(() => {
this.state = 'error'
this.hasMore = false
})
}
}
#computed
get females () {
return this.users.filter(user => user.gender === 'female')
}
#computed
get males () {
return this.users.filters(user => user.gender === 'male')
}
}
const store = new UserStore();
export default store;
If I remove #computed the application loads.

The reason for my error was incorrect .babelrc configuration with Babel 7.
Failing
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[ "#babel/plugin-proposal-decorators", { "decoratorsBeforeExport": true } ],
"transform-class-properties",
"#babel/plugin-transform-runtime"
]
}
Working
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[ "#babel/plugin-proposal-decorators", { "legacy": true } ],
[ "#babel/plugin-proposal-class-properties", {
"loose": true
}],
"#babel/plugin-transform-runtime"
]
}

Related

How to properly define a CodeMirror language?

I'm trying to provide a basic autocompletion for something like this:
db.collection("Items").where("name", "==", "temp").limit(1).get();
Here's the code I have so far, using StreamLanguage of CodeMirror 6:
import {
IndentContext,
LanguageSupport,
StreamLanguage,
StringStream
} from "#codemirror/language";
import { tags as t } from "#lezer/highlight";
export const FireStoreLanguage = StreamLanguage.define({
name: "firestore",
startState: (indentUnit: number) => {
return {};
},
token: (stream: StringStream, state: any = {}): string | null => {
console.log(stream);
if (stream.match("db")) {
state.db = true;
return "keyword";
}
if (stream.match(".")) {
if (state.db) {
state.db = false;
state.collection = true;
return "keyword";
} else if (state.collection) {
state.collection = false;
state.where = true;
return "keyword";
} else if (state.where) {
state.where = false;
state.limit = true;
return "keyword";
} else if (state.limit) {
state.limit = false;
return "keyword";
}
}
if (stream.match("collection")) {
if (state.db) {
state.collection = true;
return "keyword";
}
}
if (stream.match("where")) {
if (state.collection) {
state.where = true;
return "keyword";
}
}
if (stream.match("limit")) {
if (state.where) {
state.limit = true;
return "keyword";
}
}
if (stream.match("get")) {
if (state.limit) {
state.limit = false;
return "keyword";
}
}
if (stream.match(/"(?:[^\\"]|\\.)*"/)) {
if (state.collection) {
return "string";
}
if (state.where) {
state.where = false;
state.whereValue = true;
return "string";
}
if (state.whereValue) {
state.whereValue = false;
return "string";
}
if (stream.match("==")) {
if (state.whereValue) {
state.whereValue = false;
state.whereOperator = true;
return "operator";
}
}
if (stream.match(/[0-9]+/)) {
if (state.limit) {
return "number";
}
}
}
stream.next();
return null;
},
blankLine: (state: {}, indentUnit: number): void => {},
copyState: (state: {}) => {},
indent: (
state: {},
textAfter: string,
context: IndentContext
): number | null => {
return 1;
},
languageData: {
commentTokens: { line: ";" },
},
tokenTable: {
db: t.keyword,
dot: t.punctuation,
collection: t.keyword,
get: t.keyword,
lParen: t.punctuation,
rParen: t.punctuation,
string: t.string,
},
});
export function firestore() {
return new LanguageSupport(FireStoreLanguage);
}
In React, here's how I use it(after building it):
import CodeMirror from "#uiw/react-codemirror";
import React from "react";
import { firestore } from "./firestore";
function App() {
const onChange = React.useCallback((value, viewUpdate) => {
console.log("value:", value);
}, []);
return (
<CodeMirror
value={``}
height="100vh"
extensions={[firestore()]}
onChange={onChange}
/>
);
}
export default App;
The editor loads okay, but no autocompletion is provided while I type!
What am I doing wrong or missing in the code above?
I was missing these parts:
export const FireStoreCompletion = FireStoreLanguage.data.of({
autocomplete: completeFromList([
{ label: "db", type: "namespace" },
{ label: "collection", type: "function" },
{ label: "where", type: "function" },
{ label: "limit", type: "function" },
{ label: "get", type: "function" },
]),
});
export function firestore() {
return new LanguageSupport(FireStoreLanguage, [FireStoreCompletion]);
}

React-Query: useInfiniteQuery

So, I have looked through the docs and answers on here and I'm still needing some help:
index.tsx
const getInfiniteArticles = ({ pageParams = 0 }) => {
const res = await axios.get('/api/articles', { params: { page: pageParams } });
return res.data;
}
api/articles.ts
const getArticles = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const { page } = req.query;
const pageNum = Number(page);
const data = await NewsService.getArticles(getRange(pageNum));
return res.status(200).json({
data,
previousPage: pageNum > 0 ? (pageNum - 1) : null,
nextPage: pageNum + 1,
});
} catch (err) {
res.json(err);
res.status(405).end();
}
};
export default getArticles;
index.tsx
const { data: articlePages, fetchNextPage } = useInfiniteQuery(
'infinite-articles',
getInfiniteArticles,
{
getNextPageParam: (lastPage, allGroups) => {
console.log('lastPage: ', lastPage);
console.log('allGroups: ', allGroups);
return lastPage.nextPage;
}
});
const handleLoadMore = () => {
fetchNextPage();
};
console after clicking next page:
lastPage: { data: Array(50), previousPage: null, nextPage: 1}
allGroups: [
{ data: Array(50), previousPage: null, nextPage: 1},
{ data: Array(50), previousPage: null, nextPage: 1},
]
Any help on why I'm getting the same groups is appreciated! :)
So, it turns out my structure wasn't correct
const {
fetchNextPage,
fetchPreviousPage,
hasNextPage,
hasPreviousPage,
isFetchingNextPage,
isFetchingPreviousPage,
...result
} = useInfiniteQuery(queryKey, ({ pageParam = 1 }) => fetchPage(pageParam), {
...options,
getNextPageParam: (lastPage, allPages) => lastPage.nextCursor,
getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,
})
queryFn: (context: QueryFunctionContext) => Promise<TData>
The queryFn is supposed to be a synchronous function that returns a Promise
I was either passing an async function or I was returning the TData not a promise.
updated and working:
const getInfiniteArticles = ({ pageParam = 0 }) => axios.get('/api/articles', { params: { page: pageParam } });
const { data: articlePages, fetchNextPage } = useInfiniteQuery('articles', getInfiniteArticles, {
getNextPageParam: (lastPage, pages) => {
// the returned axios response
return lastPage.data.nextPage;
}
});
Reference Page

mongodb model contain changed on calling a function levelQuestion

Here is the code for schema
schema stores questions for a particular course and which contains chapter and there question
questions: [
{
Chapter: String,
chques: [
{
description: String,
questions: [
{
question: String,
options: [String],
answer: Number,
Explanation: String,
code: { type: String, default: null },
images: [{ type: String, default: null }],
level: String
}
]
}
]
}
],
Here is the code for route
Router.get(
"/queformock/:course_id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Courses.findOne({ _id: req.params.course_id })
.lean()
.exec()
.then(course => {
if (!course) res.status(404).json({ course: "course not found" });
else {
let coursepass = Object.assign({}, course);
console.log("coursepass1: ", coursepass); //before calling levelQuestion it output as expected
let level2 = levelQuestion(coursepass, "medium");
console.log("coursepass2: ", coursepass);
let level3 = levelQuestion(coursepass, "hard");
console.log("coursepass3: ", coursepass);
res.json(level2);
}
});
}
);
Here is the levelQuestion function code
function levelQuestion(coursed, type) {
let arr = [];
coursed.questions.forEach(item => {
item.chques.forEach(i => arr.unshift(i));
});
arr.forEach(item => {
_.remove(item.questions, i => {
return i.level !== type;
});
});
_.remove(arr, item => {
return item.questions == false;
});
return arr;
}
now the problem is on every function call of levelQuestion coursepass is changed...why??

VueFormGenerator, Custom Fieds didn't update value in model

I try to create my custom field.
so i do this :
import Vue from 'vue';
import Datepicker from 'vuejs-datepicker';
import VueFormGenerator from 'vue-form-generator';
Vue.component('fieldDatePicker', {
template: '<datepicker :placeholder="schema.placeholder" v-model="datePicker_model"></datepicker>',
components: {
Datepicker,
},
data: function() {
return {
datePicker_model: '',
};
},
mixins: [VueFormGenerator.abstractField],
mounted() {
this.datePicker_model = this.schema.default;
},
computed: {
value: {
get: function() {
return this.$moment(this.datePicker_model).format('DD-MM-YY')
},
set: function(newValue) {
throw 'TODO : ' + newValue;
// TODO converte and set value ! this.datePucker_model = newValue;
},
},
},
});
But my component didn't update the model of VueFormGenerator ...
What i forget ???
i add this to my component and it work ;)
watch: {
datePicker_model: function(newValue, OldValue) {
if(this.format(newValue) !== this.format(OldValue)) {
this.setModelValueByPath(this.schema.model, this.format(newValue));
}
},
},

ionic2 modal error no data sending

When i use alertCtrl like this data is going to db it's working well.
addTodo(){
let prompt = this.alertCtrl.create({
title: 'add',
message: 'add',
inputs: [
{
name: 'title'
},
{
name: 'kan'
},
{
name: 'geos'
},
{
name: 'geod'
},
{
name: 'sahip'
}
],
buttons: [
{
text: 'İptal'
},
{
text: 'Kaydet',
handler: todo => {
if(todo){
this.showLoader();
this.todoService.createTodo(todo).then((result) => {
this.loading.dismiss();
this.todos = result;
console.log("todo created");
}, (err) => {
this.loading.dismiss();
console.log("not allowed");
});
}
}
}
]
});
prompt.present();
}
But when i try to use modal , showloader is running but createtodo is not working , no data is going to db .
addTodo(){
let modal = this.modalCtrl.create(KaneklePage);
modal.onDidDismiss(todo => {
if(todo){
this.showLoader();
this.todoService.createTodo(todo).then((result) => {
this.loading.dismiss();
this.todos = result;
console.log("todo created");
}, (err) => {
this.loading.dismiss();
console.log("not allowed");
});
}
});
modal.present();
}
This is dismiss code in modalpage
save(): void {
let todo = {
title: this.title,
kan: this.kan,
geos: this.geos,
geod: this.geod,
sahip: this.sahip
};
this.viewCtrl.dismiss(todo);
}