I am new to rxjs Observables. I am trying simple login page application. When I am sending correct credentials, code is working fine and loading spinner also stops rendering. When credentials are invalid then code stops working and spinner also stays on the page. I have to reload the page to make it work again.
Here's the code :
import constants from "../constants";
import "rxjs";
import { ajax } from "rxjs/observable/dom/ajax";
import { loginBody } from "../utils/bodyCreator";
import {
showLoadingSpinner,
hideLoadingSpinner
} from "../actions/LoadingOverlayActions";
const sessionCreated = payload => ({
type: constants.sessionCreated,
response: payload
});
export const tryLoginEpic = (action$, store) =>
action$
.ofType(constants.tryLogin)
.map(() => store.dispatch(showLoadingSpinner()))
.mergeMap(action =>
ajax
.post(constants.loginEndPoint, loginBody(store.getState()), {
"Content-Type": "application/json"
})
.map(data => store.dispatch(sessionCreated(data.response)))
.map(() => store.dispatch(hideLoadingSpinner()))
.catch(err => store.dispatch(hideLoadingSpinner()))
);
Please help me how to do this and what is wrong in this code?
Thanks
You need to use .catch operator in a different way. For example, return empty Observable (or other action), something like:
.catch(error => {
store.dispatch(hideLoadingSpinner());
return Observable.empty();
})
see official documentation on catchError operator
Related
I'm new in ReactJS. Now trying to make the GET request from an API using axios with the following code. But page loads earlier than the request so my state gives an empty array. I tried to solve it by using async and await but I couldn't succeed it since I don't know the React well, I guess. Please help, thank you a lot.
import {useEffect, useState} from 'react';
import axios from 'axios';
function NewsPage(){
const [news, setNews] = useState([]);
useEffect(() => {
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://api.newscatcherapi.com/v2/search',
params: {q: 'obama', lang: 'en', sort_by: 'relevancy', page: '1'},
headers: {
'x-api-key': '**************'
}
};
axios.request(options)
.then(function (response) {console.log(response.data.articles)})
.then(response => setNews(response.data.articles))
.catch(function (error) {console.error(error)})
},[]);
return (
<div>
Hello
{news.map((eachnews) => {
return <div key={eachnews.title}>
<h2>{eachnews.author}</h2>
</div>
})}
</div>
)
}
export default NewsPage
This is normal behavior of React. Older frameworks block the whole page while loading, but React renders the page already while loading.
It is a design decision that makes perfectly sense. You can add a loading animation or a skeleton during loading. This is considered better practice instead of leaving the whole page white. Especially because you can then do good error handling that doesn't interrupt the UI.
I have a Component which makes a axios get
Component <using axios instance> {
componentDidMount(){
axios.get('myurl.jn').then(ingredients => { <wrong url>
}).catch( error => {
console.log(error) // dosent even show here as we donot propagate the error
})
}
}
export default hoc(Component,axiosInstance)
Higher Order Funcfor Component
const ErrorHandler = (WrapperComponent, axios) => {
return class extends Component {
componentDidMount(){
axios.interceptors.request.use(req => {
console.log(req) // none
this.setState({error : null});
return req;
});
axios.interceptors.response.use(res => res,(error) => {
console.log(error) // none
this.setState({error : true});
});
}
I tried adding logger and breakpoints to all the places in the hoc which uses the axios instance but to no effect nothing gets called .
The only place the interceptor is picked up in the place where i create the instance why and how do we solve this. The console for browser throws 404 but not caught by interceptor.
I am very new to react and axios just learning for past week please pardon if not following any proper guidelines
So I am trying to develop a search bar component in a React application where you can type in a users last name and that request will go to the Behance API and pull up that users data.
I am stuck on this:
axios
.get(API_URL + 'users?q=' + 'matias' + '&client_id=' + API_KEY + '&callback=')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
alert(error.message);
});
I have tried wrapping the above in a const userSearch = () => {}, but that takes me a step farther from my goal. With the above I actually do get 200 statuses, but there is the CORS issue. I just can't seem to put together a callback that is not undefined in there, nevermind that this is a search bar implementation so I am going to have to refactor the above. I was just wanting to see some data returned.
One of the nicest things in Axios, is the seperation between request argument.
For example, the url should be only URL: API_URL + '/users'.
The parameters you want to pass, should be sent as an object.
The promise of the axios get, is the callback you are looking for.
Therefore, your request should look like this:
axios.get(API_URL + 'users', {
params: {
q: 'matias',
client_id: API_KEY,
}
})
.then(response => {
- success callback actions -
})
.catch(error => {
- error callback actions -
});
So I had refactored my axios code and I was still getting CORS errors, but after reading a couple of blogs online saying that with fetch() and jQuery you could get around that, in particular this SO article: Loading Data from Behance API in React Component
I actually duplicated Yasir's implementation like so:
import $ from 'jquery';
window.$ = $;
const API_KEY = '<api-key>';
const ROOT_URL = `https://api.behance.net/v2/users?client_id=${API_KEY}`;
export const FETCH_USER = 'FETCH_USER';
export function fetchUser(users) {
$.ajax({
url: `${ROOT_URL}&q=${users}`,
type: 'get',
data: { users: {} },
dataType: 'jsonp'
})
.done(response => {})
.fail(error => {
console.log('Ajax request fails');
console.log(error);
});
return {
type: FETCH_USER
};
}
And sure enough, no more CORS error and I get back the users data in my Network > Preview tabs. Not very elegant, but sometimes you are just trying to solve a problem and at wits end.
Im using React with axios to read some data from my backend.
I have a BetBuilder js using axios to read like this:
componentDidMount() {
axios.get('http://localhost:8080/api/matches/')
.then(response => {
console.log("Dentro do didmount");
this.setState({ matches: response.data._embedded.matches });
console.log(this.state.matches);
console.log("Dentro do didmount");
});
Everything works fine here. So in my render method i pass this data to a Match component:
var matches = this.state.matches.map(match =>
<Match key={match._links.self.href} match={match}/>
);
In my Match.js class, I try to retrieve other data with axios. But it just doesnt work. In my debug it never enters on the response function.
const awayUrl = this.props.match._links.away.href;
const homeUrl = this.props.match._links.home.href;
axios.get("http://localhost:8080/api/matches/4/away")w
.then(response => {
console.log("Dentro do away");
this.setState({ away: response.data._embedded });
console.log(this.state.away);
console.log("Dentro do away");
})
.catch((error) => {
console.log("error",error)
});
What Im missing? Theres something on the Axios lifecycle that i cant use it in the same request? Why this axios.get method is never called, and dont throws any exception too?
Thanks
I am building my first React Native app and use Redux for the data flow inside my app.
I want to load some data from my Parse backend and display it on a ListView. My only issues at the moment is that for some reason, the request that I create using fetch() for some reason isn't actually fired. I went through the documentation and examples in the Redux docs and also read this really nice blog post. They essentially do what I am trying to achieve, but I don't know where my implementation differs from their code samples.
Here is what I have setup at the moment (shortened to show only relevant parts):
OverviewRootComponent.js
class OverviewRootComponent extends Component {
componentDidMount() {
const { dispatch } = this.props
dispatch( fetchOrganizations() )
}
}
Actions.js
export const fetchOrganizations = () => {
console.log('Actions - fetchOrganizations');
return (dispatch) => {
console.log('Actions - return promise');
return
fetch('https://api.parse.com/1/classes/Organization', {
method: 'GET',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-REST-API-Key': 'xxx',
}
})
.then( (response) => {
console.log('fetchOrganizations - did receive response: ', response)
response.text()
})
.then( (responseText) => {
console.log('fetchOrganizations - received response, now dispatch: ', responseText);
dispatch( receiveOrganizations(responseText) )
})
.catch( (error) => {
console.warn(error)
})
}
}
When I am calling dispatch( fetchOrganizations() ) like this, I do see the logs until Actions - return promise, but it doesn't seem to actually to fire off the request. I'm not really sure how how I can further debug this or what resources to consult that help me solve this issue.
I'm assuming that Redux is expecting a Promise rather than a function.. Is that true?
If so, I think your return function may not be working.
You have a new line after your return, and it's possible JavaScript is (helpfully) inserting a semicolon there.
See here: Why doesn't a Javascript return statement work when the return value is on a new line?