Typescript RxJS ajax undefined this context - ajax

is question is very similar to many others already answered. But these solutions didnt work. Here is the problem:
Having a Typescript class which calls an RxJS.ajaxPost() On Response pipe or callback "this" is undefined.
Usually I just use arrow functions ()=>{} to get rid of it. But it dont works in this case.
Why? How to handle ajax calls correctly and using responses?
export class Store {
count: number = 0;
getRest(): void {
ajaxPost('https://httpbin.org/delay/2')
.pipe(
tap((response) => {
console.log('response: ', response, this);
this.count += 1;
}),
catchError(error => {
console.log('error: ', error);
return of(error);
})
)
.subscribe((resp) => {
console.log("subs resp", resp, this);
});
}
}

Iam sorry, the error lies above!
for tests I had made 2 react components and wanted to use the getRest function directly. Of course this wont work.
In compare the upper function "addCount()" works fine.
My Fail. Sry.
export const Controls = observer(_Controls);
function _Controls(props: {store:Store}): any {
return <div>
<button onClick={() => props.store.addCount(2)}>Add 2 = {props.store.count}</button>
</div>;
}
export const Controls2 = observer(_Controls2);
function _Controls2(props: {store:Store}): any {
return <div>
<button onClick={props.store.getRest} title="add">Add Rest 3 = {props.store.count}</button>
</div>;
}

Related

Multiple subscriptions causing source stream to fire twice

I want to use RxJS to listen to clicks, perform a transaction, and keep track of the transaction status:
function performTransaction() {
const status = {
'0': 'pending',
'1': 'success'
}
return interval(1000).pipe(take(2), map((i) => status[`${i}`]))
}
const click$ = new Subject<void>()
const claimTxnState$ = click$.pipe(switchMap(() => {
console.log('performing transaction') // -> runs once which is expected
return performTransaction()
}))
claimTxnState$.subscribe((v) => {
console.log('claimTxnState', v);
})
export default function App() {
return (
<div className="App">
<button onClick={() => click$.next()}>click me</button>
</div>
);
}
This causes performing transaction to be output once, as is expected.
But I want to pipe claimTxnState$ to more places:
const claimIsPending$ = claimTxnState$.pipe(map((claim) => claim === 'pending'))
claimIsPending$.subscribe((v) => {
console.log('claimIsPending', v);
})
This now causes performing transaction to be output twice, which I understand because these are cold observables that get recreated on each subscription. But I don't want this. I only want my performTransaction to get called once. How can I achieve this?
Complete example.
I found the answer as I was typing the question. I need to use the share operator to convert the observable from cold to hot. This has the effect of sharing claimTxnState$ between all subscribers (i.e. .pipes(...)):
const claimTxnState$ = click$.pipe(
switchMap(() => {
console.log('performing transaction')
return performTransaction()
}),
share() // <- this is the interesting line
)
Sandbox.
More detail.

Vue js function countSubcategories() returns [object Promise]

countSubcategories() function returns [object Promise] where it should return row counts of mapped subcategories.
This code is in vue.js & Laravel, Any suggestions on this?
<div v-for="(cat,index) in cats.data" :key="cat.id">
{{ countSubcategories(cat.id) }} // Here subcategories row counts should be displayed.
</div>
<script>
export default {
data() {
return {
cats: {},
childcounts: ""
};
},
created() {
this.getCategories();
},
methods: {
countSubcategories(id) {
return axios
.get("/api/user-permission-child-count/" + `${id}`)
.then(response => {
this.childcounts = response.data;
return response.data;
});
},
getCategories(page) {
if (typeof page === "undefined") {
page = 1;
}
let url = helper.getFilterURL(this.filterpartnerForm);
axios
.get("/api/get-user-permission-categories?page=" + page + url)
.then(response => (this.cats = response.data));
}
}
};
</script>
As Aron stated in the previous answer as you are calling direct from the template the information is not ready when the template is rendered.
As far as I understood you need to run getCategories first so then you can fetch the rest of your data, right?
If that's the case I have a suggestion:
Send an array of cat ids to your back-end and there you could send back the list of subcategories you need, this and this one are good resources so read.
And instead of having 2 getCategories and countSubcategories you could "merge" then like this:
fetchCategoriesAndSubcategories(page) {
if (typeof page === "undefined") {
page = 1;
}
let url = helper.getFilterURL(this.filterpartnerForm);
axios
.get("/api/get-user-permission-categories?page=" + page + url)
.then(response => {
this.cats = response.data;
let catIds = this.cats.map(cat => (cat.id));
return this.countSubcategories(catIds) // dont forget to change your REST endpoint to manage receiving an array of ids
})
.then(response => {
this.childcounts = response.data
});
}
Promises allow you to return promises within and chain .then methods
So in your created() you could just call this.fetchCategoriesAndSubcategories passing the data you need. Also you can update your template by adding a v-if so it doesn't throw an error while the promise didn't finish loading. something like this:
<div v-if="childCounts" v-for="(subcategorie, index) in childCounts" :key="subcategorie.id">
{{ subcategorie }} // Here subcategories row counts should be displayed.
</div>
Hello!
Based on the provided information, it could be 2 things. First of all, you may try replacing:
return response.data;
with:
console.log(this.childcounts)
and look in the console if you have the correct information logged. If not, it may be the way you send the information from Laravel.
PS: More information may be needed to solve this. When are you triggering the 'countSubcategories' method?
I would do all the intial login in the component itself, and not call a function in template like that. It can drastically affect the performance of the app, since the function would be called on change detection. But first, you are getting [object Promise], since that is exactly what you return, a Promise.
So as already mentioned, I would do the login in the component and then display a property in template. So I suggest the following:
methods: {
countSubcategories(id) {
return axios.get("..." + id);
},
getCategories(page) {
if (typeof page === "undefined") {
page = 1;
}
// or use async await pattern
axios.get("...").then(response => {
this.cats = response.data;
// gather all nested requests and perform in parallel
const reqs = this.cats.map(y => this.countSubcategories(y.id));
axios.all(reqs).then(y => {
// merge data
this.cats = this.cats.map((item, i) => {
return {...item, count: y[i].data}
})
});
});
}
}
Now you can display {{cat.count}} in template.
Here's a sample SANDBOX with similar setup.
This is happen 'cause you're trying to render a information who doesn't comeback yet...
Try to change this method inside created, make it async and don't call directly your method on HTML. Them you can render your variable this.childcounts.

Getting "Unreachable code no-unreachable" in ReactJS

I am new to create GET requests in React. I am trying to fetch media_id from Instagram Content when someone enters the url in the input field. The interesting thing is I do get response in Inspector for the following GET request but I am not sure how to properly execute this.
Following is my Component Code.
import React, { Component } from 'react';
export default class UrlInput extends Component {
constructor(props){
super(props);
this.state = {
term: '',
mediaid: ''
};
this.onInputChange = this.onInputChange.bind(this);
}
componentDidMount(){
const url = 'https://api.instagram.com/oembed/?url=http://instagram.com/p/Y7GF-5vftL/';
fetch(url).then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
},
networkError => console.log(networkError.message)).then(jsonResponse => {
return jsonResponse;
console.log(jsonResponse);
});
}
render(){
return (
<div className='search-bar'>
<input
value= {this.state.term}
onChange={ event => this.onInputChange(event.target.value)} />
<div>{this.state.term}</div>
</div>
);
}
onInputChange(term){
this.setState({term});
}
}
no-unreachable is just a warning that tells you that you have unreachable code in your code. In this case, it is the console.log(jsonResponse) after return jsonResponse
It is unreachable because when the code find a return statement, it will just break out of the function and not continue any further, thus the console.log(jsonResponse) will never be called.
I faced the same problem. Seems it is because the parenthesis of return should be inline like return (
and not like
return
(
This solved problem for me
Remove console.log() after the return value
Had this same issue.
Removing the semicolon on the line the warning was on solved the problem.

Make server validation using redux-form and Fetch API

How to make server-side validation using redux-form and Fetch API?
There are "Submit Validation" demo provided in the docs which says that recommended way to do server side validation is to return a promise from the onSubmit function. But where should I place that promise?
As I understood onSubmit function should be my action.
<form onSubmit={this.props.addWidget}>...
Where this.props.addWidget is actually my action, provided below.
import fetch from 'isomorphic-fetch';
...
function fetchAddWidget(widget, workspace) {
return dispatch => {
dispatch(requestAddWidget(widget, workspace));
return fetch.post(`/service/workspace/${workspace}/widget`, widget)
.then(parseJSON)
.then(json => {
dispatch(successAddWidget(json, workspace));
DataManager.handleSubscribes(json);
})
.catch(error => popupErrorMessages(error));
}
}
export function addWidget(data, workspace) {
return (dispatch, getState) => {
return dispatch(fetchAddWidget(data, workspace));
}
}
As you see I use fetch API. I expected that fetch will return promise and redux-form will catch it but that doesn't work. How to make it work with promise from example?
Also from the demo I can not understand what should be provided in this.props.handleSubmit function. Demo does not explain this part, as for me.
Here's my take on using fetch based on the example at http://erikras.github.io/redux-form/#/examples/submit-validation.
...but where should I place that promise?
...what should be provided in this.props.handleSubmit?
The detail is in the comments below; sorry that the code blocks require a bit of scrolling to read :/
components/submitValidation.js
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { myHandleSubmit, show as showResults } from '../redux/modules/submission';
class SubmitValidationForm extends Component {
// the following three props are all provided by the reduxForm() wrapper / decorator
static propTypes = {
// the field names we passed in the wrapper;
// each field is now an object with properties:
// value, error, touched, dirty, etc
// and methods onFocus, onBlur, etc
fields: PropTypes.object.isRequired,
// handleSubmit is _how_ to handle submission:
// eg, preventDefault, validate, etc
// not _what_ constitutes or follows success or fail.. that's up to us
// I must pass a submit function to this form, but I can either:
// a) import or define a function in this component (see above), then:
// `<form onSubmit={ this.props.handleSubmit(myHandleSubmit) }>`, or
// b) pass that function to this component as
// `<SubmitValidationForm onSubmit={ myHandleSubmit } etc />`, then
// `<form onSubmit={this.props.handleSubmit}>`
handleSubmit: PropTypes.func.isRequired,
// redux-form listens for `reject({_error: 'my error'})`, we receive `this.props.error`
error: PropTypes.string
};
render() {
const { fields: { username, password }, error, handleSubmit } = this.props;
return (
<form onSubmit={ handleSubmit(myHandleSubmit) }>
<input type="text" {...username} />
{
// this can be read as "if touched and error, then render div"
username.touched && username.error && <div className="form-error">{ username.error }</div>
}
<input type="password" {...password} />
{ password.touched && password.error && <div className="form-error">{ password.error }</div> }
{
// this is the generic error, passed through as { _error: 'something wrong' }
error && <div className="text-center text-danger">{ error }</div>
}
// not sure why in the example #erikras uses
// `onClick={ handleSubmit }` here.. I suspect a typo.
// because I'm using `type="submit"` this button will trigger onSubmit
<button type="submit">Log In</button>
</form>
);
}
}
// this is the Higher Order Component I've been referring to
// as the wrapper, and it may also be written as a #decorator
export default reduxForm({
form: 'submitValidation',
fields: ['username', 'password'] // we send only field names here
})(SubmitValidationForm);
../redux/modules/submission.js
// (assume appropriate imports)
function postToApi(values) {
return fetch( API_ENDPOINT, {
credentials: 'include',
mode: 'cors',
method: 'post',
body: JSON.stringify({values}),
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': CSRF_TOKEN
}
}).then( response => Promise.all([ response, response.json()] ));
}
export const myHandleSubmit = (values, dispatch) => {
dispatch(startLoading());
return new Promise((resolve, reject) => {
// postToApi is a wrapper around fetch
postToApi(values)
.then(([ response, json ]) => {
dispatch(stopLoading());
// your statuses may be different, I only care about 202 and 400
if (response.status === 202) {
dispatch(showResults(values));
resolve();
}
else if (response.status === 400) {
// here I expect that the server will return the shape:
// {
// username: 'User does not exist',
// password: 'Wrong password',
// _error: 'Login failed!'
// }
reject(json.errors);
}
else {
// we're not sure what happened, but handle it:
// our Error will get passed straight to `.catch()`
throw(new Error('Something went horribly wrong!'));
}
})
.catch( error => {
// Otherwise unhandled server error
dispatch(stopLoading());
reject({ _error: error });
});
});
};
Please chime in with comments if I've missed something / misinterpreted, etc, and I'll amend :)
It turned out that there are undocumented property returnRejectedSubmitPromise which must be set to true.

How do I keep context in react without stringing .bind(this)?

I'm using react to retrieve data from parse, manipulate it in my own function, and then update a component in the render.
The problem is that I can't update the state within my own, convoluted function unless I attach a string of bind(this). The entire component looks like this:
React.Component({
getInitialState: function () {
return{
isloading:true
}
},
componentDidMount: function(){
this.myStupidFunction()
},
myStupidFunction : function(){
(
(
(nested parse queries that eventually ...
return an object and set isloading:false).bind(this))
.bind(this))
.bind(this)
},
render: function (){
if (this.state.isloading) {
return(
<Text "...isloading"/>
)
} else {
return(
...actually return important stuff...
)
}
}
})
What is the smarter way to do this? Do I need to really .bind(this) for every nested function?
There are a few ways to maintain the context of your component.
Use ES6 Arrows
If you use ES6 arrows to define your functions. Arrow functions force the inner context of this to be the same as the outer context, regardless of how the function is called.
parse.find({
success: results => {
// this is correct
console.log(this);
}
});
I think this is the most elegant solution, but not all browsers support arrow functions yet.
Use Component Methods
React automatically binds this into each of the top level methods on your component. They are always guaranteed to have the correct context.
onSuccess: function() {
// this is correct
console.log(this);
},
componentWillMount: function() {
parse.find({
success: this.onSuccess
});
}
This is also fairly elegant, in my opinion. It lets React deal with the messiness of context whilst you just write code. However, it can mean that you end up with far too many methods at the top level of your component, so use it sparingly.
As an Argument
Some functions, such as map allow you to optionally pass a context to use as this as a final argument. This allows you to maintain the correct context without .bind(this).
data.map(function() {
console.log(this);
// this is correct
}, this);
This only works for some methods, so it's not really a universal solution.
Alias this
Create a reference to this and use that instead.
var __this__ = this;
parse.find({
success: results => {
// __this__ is correct
console.log(__this__);
}
});
This hack has been around forever in Javascript, but I don't think it's a great way to solve the problem.
Use ES7 Function Bind
For those who like to Javascript on the edge, you could also achieve this using the ES7 function bind syntax proposal — currently implemented in Babel.
parse.find({
success: this::function(results) {
// this is correct
console.log(this);
}
});
This requires using experimental proposal stage features of ES7. You may not want to start using it yet, but it's definitely interesting to be aware of. The value on the left hand side will be bound into the function on the right, as this.
Use a closure at the beginning of the function to capture this. It will be usable in any nested structure. The conventional names for such a closure are self _this and that. I prefer self.
myStupidFunction : function(){
var self = this;
someAsyncCall(1,2, function(result) {
//some nested stuff
anotherAsyncCall(1,2 function(innerResult) {
self.setState(innerResult);
});
});
}
one solution could be using local variable
myStupidFunction:function(){
var that=this
ParseReact.Mutation.Create('Place', {
name: 'New Place',
user: Parse.User.current()
})
.dispatch()
.then(function() {
that.refreshQueries();
});
}
Using ES7 Property Initalizer Syntax, currently implemented in Babel.
The key is the methodName = () => { //method return }
You can read more here.
import React from 'react';
export default class Note extends React.Component {
constructor(props) {
super(props);
this.state = {
editing : false
}
}
render() {
const editing = this.state.editing;
return (
<div>{ editing ? this.renderEdit() : this.renderTask() }</div>
)
}
renderEdit = () => {
return (
<input type="text"
className="edit-input"
autoFocus={true}
defaultValue={this.props.task}
onBlur={this.finishEdit}
onKeyPress={this.checkEnter} />
)
}
renderTask = () => {
const onDelete = this.props.onDelete;
return (
<div onClick={this.edit}>
<span className="task-body">{this.props.task}</span>
{ onDelete ? this.renderDelete() : null }
</div>
)
}
renderDelete = () => {
return (
<button className="delete-btn" onClick={this.props.onDelete}>x</button>
)
}
edit = () => {
this.setState({
editing : true
})
}
checkEnter = (e) => {
if(e.key === "Enter") {
this.finishEdit(e);
}
}
finishEdit = (e) => {
this.props.onEdit(e.target.value);
this.setState({
editing : false
})
}
}
// Note: Sample class from project above.

Resources