JavaScript Flow types - Type parameter not bound to return value of function - flowtype

I'm trying to create a function with a type parameter which returns an object with a property which is a function returning that generic type. The following is reduced to a minimal example. What incorrect assumptions/syntax mistakes am I making?
type chatType = {
name: string,
}
const cake = <T>(asdf: T) => ({
pizza: (): T => asdf,
})
cake<chatType>({ name: 'abcde' }).pizza().name
The error:
Error ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ asdf.js:24:43
Cannot get cake<...>(...).pizza().name because property name is
missing in T [1].
[1] 21│ pizza: (): T => asdf,
22│ })
23│
24│ cake<chatType>({ name: 'abcde' }).pizza().name
25│

Related

Ionic and Firebase .update(): Nested Arrays are not supported

I'm having this issue while I'm trying to perform a crud update function. To put into context, this is an Ionic app with Firebase. This is an app in which the user will be able to create events and update them at a later stage if they want. However, I'm not being able to perform the update with the following error:
ERROR FirebaseError: Function DocumentReference.update() called with invalid data. Nested arrays are not supported (found in document Events/XWtRgH04iEG9IUIqMrgX)
Below are highlighted the function that will save an event after being updated and the service that contains the update function. Any help is greatly appreciated!
saveEvent(event) {
let id = event.id;
let evtSave = {
id: id,
createdAt: event['createdAt'],
createdBy: event['createdBy'],
updatedAt: Date.now(),
part: event['part'] || ['No participants'],
comments: event['comments'] || ['No comments'],
type: event['type'],
title: event['title'],
date: event['date'],
time: event['time'],
map: event['map'],
players: event['players'],
location: event['location'],
description: event['description'],
image: event['image']
};
console.log('saveEvent: ', evtSave);
this.eventServ.updateEvents(id, evtSave)
.then(res => {
this.searchEvents();
console.log('Event: ', res);
this.myAlert('Event successfully updated');
this.mode = 'listMode';
});
Below is the code contained in the service:
updateEvents(eventID, event){
return this.firestore.collection('Events').doc(eventID).update(({
id: event.id,
createdAt: event.date,
createdBy: event.createdBy,
updatedAt: Date.now(),
part: [event.part],
comments: [],
type: event.type,
title: event.title,
date: event.dateMilis,
time: event.time,
map: event.map,
players: event.players,
location: event.location,
description: event.description || 'No description...',
image: event.image || 'No image...',
})).catch((error)=>{
console.log('Error: ', error);
})
and finally a screenshot of how an event looks like in firebase:
At one place in your code you have part: event['part'] || ['No participants'], which will set part to an array of stringy, containing exactly one participant.
Later, when you save, you do: part: [event.part], which I assume can lead to the case where you will get part: [['No participants']].
This is a nested array and as firebase tells you in the error message, this is not supported in firestore.

Mirage Passthrough returns Response Object instead of JSON data returned from network call

I am getting an error:
Mirage: Your Ember app tried to GET 'http://localhost:3006/data.json',
but there was no route defined to handle this request.
Define a route that matches this path in your mirage/config.js file.
Did you forget to add your namespace?
So following the documentation of mirage i added this:
this.passthrough('http://localhost:3006/data.json');
Even though after adding passthrough, I am getting such Response instead of JSON Object returned from the network api call.
The Actual Request i am making is:
fetch(`${host}/data.json`)
.then(res => res.json())
.then(data => {
// my operation on data
});
The response i am getting is:
{bodyUsed: true
headers: Headers {map: {…}}
ok: true
status: 200
statusText: "OK"
type: "default"
url: "http://localhost:3006/data.json"
_bodyInit: null
_bodyText: ""}
But I am expecting:
{
"files":
{
"x": "any",
"a": "any",
"b": "any",
"c": "any"
}
}
I kept a debugger in Pretender.js which is sending the FakeRequest and there in its object, I see that FakeRequest has responseType="" and response as null. And somehow my responseText has value but that is not considered and response value is considered and receiving null.
Also there is a logic which is return saying
"response" in xhr ? xhr.response : xhr.responseText
In this case i have response property but its value is null. Hence according to the above condition it is returning xhr.response which is null
Thanks in Advance.

Redux saga - can't dispatch action: __webpack_require__.i(...) is not a function

I am trying to dispatch an action in a saga function in this way:
yield put(addToCart(item));
When trying to execute it, it gives the error __webpack_require__.i(...) is not a function.
"addToCart" is an action creator which I imported:
export const addToCart = product => ({
type: types.ADD_TO_CART,
payload: { product },
});
This action never fires.
The item (or product) is an object, like :
{
'id' : 5,
'thing' : 'stuff'
}
(+ other properties).
I can dispatch other actions, but this one doesn't work for some reason.
I had imported the action creator wrongly:
import addToCart from './actionCreators'
It should be:
import { addToCart } from './actionCreators'
But what kind of error is "__webpack_require__.i(...) is not a function" ? The error messages are worthless, they give you no clue at what the error is about.

Map operator. Different function types and accessor

i have recently updated Firebase and AngularFire2 in my Ionic project
Versions:
Firebase: 5.0.3
AngularFire2: 5.0.0-rc.10
rxjs 6.2.0
now I tried to upgrade the project from the regular map to pipe using the migration guide:
Migration guide AngularFire2 version5
But if i use exact the same example for the following code block:
///my code
let dataBaseCollection = this.store.collection('items').snapshotChanges().pipe(
map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
)
).subscribe(items => {
return items.map(item => item.key);
});
///example
afDb.list('items').snapshotChanges().pipe(
map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
)
)
I get the following exceptions:
Argument of type 'OperatorFunction' is not assignable to parameter of type 'UnaryFunction, Observable<{ const: string; return: any; }[]>>'.
Types of parameters 'source' and 'source' are incompatible.
Type 'Observable' is not assignable to type 'Observable'. Two different types with this name exist, but they are unrelated.
Property 'source' is protected in type 'Observable' but public in type 'Observable'.
I already tried the two different operator from rxjs
import { map } from 'rxjs/operators';
import { map } from 'rxjs/operators/map';
I appreciate any help.
Well, I don't know if this is the issue, but a few observations:
let dataBaseCollection is receiving a Subscription from .subscribe and not the items. You cannot return inside the subscribe, so your code should be just this:
let dataBaseCollection = this.store.collection('items').snapshotChanges().pipe(
map(actions => actions.map(a => ({ key: a.key, ...a.payload.val() })))
)
If you want to map only the keys then just do:
let dataBaseCollection = this.store.collection('items').snapshotChanges().pipe(
map(actions => actions.map(a => a.key))
)
I get it running.
I do not have a real clue, what the actual problem was. But I completely deleted my local repository and get all files new.
Then I reinstalled all NPM files. Somewhere in this area was my problem. I would guess, that any of my npm packages was the problem.
Im sorry, that I can not clarify the issue more. Maybe someone else will have the same Problem in the future and can add it here.

Redux Thunk / Eslint erro

I'm trying to build a React + Redux app, and I'm using Redux Thunk.
One of my action creators looks like this:
import api from '../api';
export const FETCH_BOOKS = 'FETCH_BOOKS';
export default () => dispatch =>
api
.books()
.perPage(-1)
.then(books =>
dispatch(books => ({
type: FETCH_BOOKS,
books,
}))
)
.catch(error =>
dispatch(e => ({
type: 'ERROR',
error: e,
}))
);
But when I run yarn run build:production I get the error(s):
ERROR in ./scripts/ll-app/actions/fetch-books.js
/Users/joneslloyd/resources/assets/scripts/ll-app/actions/fetch-books.js
9:11 warning 'books' is defined but never used no-unused-vars
11:9 error Expected an assignment or function call and instead saw an expression no-unused-expressions
11:9 error 'books' is already declared in the upper scope no-shadow
17:12 warning 'error' is defined but never used no-unused-vars
19:9 error Expected an assignment or function call and instead saw an expression no-unused-expressions
19:9 error 'error' is already declared in the upper scope
However, I want to pass the books array (returned from the async api call) to the dispatch (anonymous function passed to dispatch) to then include said books array in the action, which the reducer will receive.
Am I doing something wrong here?
Even when I rename the inner reference to books it doesn't help.
It's possible I'm overlooking something in ES6 here.. But I basically want to take the books array returned from the api call (as a parameter of the then method), and then pass it into the dispatch function inside of that, as a parameter of the anonymous function I'm passing in.
Any help with this would be excellent. Thanks!
I'm not sure if this is the source of the problem, but why do you need the inner ref to books at all? Your error msg/linter is complaining about that.
...
api
.books()
.perPage(-1)
.then(books =>
dispatch({
type: FETCH_BOOKS,
books,
})
).catch(error => dispatch({type: ERROR, error}))
why won't the above do what you want?
no function in the dispatch necessary here.
dispatch needs a plain action. A function in dispatch is giving you the error.
When you see function in dispatch in the docs, those functions are function calls that are just returning the action.
export someActionCreator = () => ({type: ACTION, payload})
dispatch(someActionCreator());
Your functions are just statements and are not returning the action to the dispatch. which would be more akin to something like
export someActionCreator = () => ({type: ACTION, payload})
dispatch(someActionCreator);
see the difference?
Hope this helps!

Resources