React Native get dynamic data - reactjs

there is a data which is changing every second in my api and i should get it dynamically to react native screen and im using setInterval
I writed a function which is send request and get data every second and i should refresh this function and i did use setInterval but im not sure about that is this healthy? also i could not solve this because i got an error that :
Possible Unhandled Promise Rejection (id: 7):
TypeError: _this2.setState is not a function. (In '_this2.setState({
kalanzaman: res.data
})', '_this2.setState' is undefined)
My func and how am i calling it :
dynamically() {
// console.log("bom")
axios.get(`http://localhost:5000/kalanzaman`)
.then(res => {
this.setState({ kalanzaman: res.data })
})
}
.
setInterval(this.dynamically, 1000)
Which way should i use for get dynamic data to react native from my api?

Instead of Http request, you can use Websocket.
It is a two-way interactive communication session between the user's browser and a server.
for example: have a look at Socket.IO

Maybe it would be better if you write it like this:
setInterval(() => {
dynamically() {
// console.log("bom")
axios.get(`http://localhost:5000/kalanzaman`)
.then(res => {
this.setState({ kalanzaman: res.data })
}).catch((error) => {
alert('Something Error')
})
}
}, 100);
You must cath() for catching the error, and put it on componentDidMount

Related

Get All The youtube video from specific channel in reactjs

I am trying to get video from a specific channel in youtube using youtube data api using reactjs.But my api query doesnot return anything.Here is what i've tried for getting the video.What am i doing wrong here.
componentDidMount() {
console.log('componentDidMount colling ...');
fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
.then(results => {
this.setState({videos: results.json()});
this.setState({playingVideoId: this.state.videos[this.index]});
console.log("videos",this.state.videos)
console.log("videos",this.state.playingVideoId)
})
}
First try to use postman to see if URL is returning correct data.
Second: setState is asynchronous which means, if you console.log right after setting state, you won't get correct results. Also, your second call to setState is using data from first call therefore you won't get right results. Just call setState once and use callback to log what you got.
componentDidMount() {
console.log('componentDidMount colling ...');
fetch('https://www.googleapis.com/youtube/v3/channels?key="MYAPIKEY"&channelId="MYCHANNELID"&part=snippet,id&order=date&maxResults=2')
.then(results => {
const videosObj = results.json();
this.setState({
videos: videosObj,
playingVideoId: videosObj[this.index]
}, (updatedState) => {
console.log("videos", updatedState.videos);
console.log("videos", updatedState.playingVideoId);
});
})
}

How to handle api error in react and show custom log

componentDidMount() {
let url = FormatUrl(`/user/`)
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
}).catch(err => {
if (err){
console.log('has error')
}
})
}
Here i am trying to fetch data from a wrong api.
And it is throwing below error.
Home.jsx:20 GET http://127.0.0.1:8000/user/ net::ERR_CONNECTION_REFUSED
I
Is there any way to hide this error and display a simple message in console without throwing
exceptions.
The promise isn't rejected by the fetch API simply because it fails to reach the endpoint. What you need to do is check the response in your first .then(). You have response.status which returns the status code, or you could use response.ok which returns true if the status code is within the 200-299 interval.
A more detailed explanation can be found here

React Axios not rendering after setState

I've got troubles with my Login component, I'm using the cointainer pattern, so i've got a component Login which manage the api call and a DumbLogin managing the input and warn the user about the response from my server.
I'm using Axios to do the api call, which use promises to do that, I'm also using arrow function to avoid troubles wiht the this, well that's what i was thinking...
Because in the end I have
TypeError: _this.setState is not a function
I tried to use a variable self to resolve that but that result in the same error.
How Am I suppose to do?
axios(all)
.then((response) => {
console.log(response);
if (response.status === 200){
this.setState({
...this.state,
spin: false,
});
let data = response.data;
this.props.connect(data.username, data.email, data.token, data.partners);
this.props.router.push('panel');
}
}).catch((error) => {
console.log(error.response);
this.setState({
spin: false,
errorLogin: 'Username or password wrong',
});
});
(spin is a boolean to inform DumbLogin that it should or not display a spinner while waiting for the response from my server)
it's because the this inside of the anonymous function inside of the then is not the this of the React component.
you need to bind the correct this(Reac Component's this) for the function which does the ajax call.
eg. if the function is:
fetchData(){
axios(all).then(...).catch(...)
}
you can bind it in the constructor:
constructor(){
this.fetchData = this.fetchData.bind(this)
}
HOWEVER!
This is not the recommended solution, you would usually dont want to do ajax call in the component... you may want redux, mobx or even redux-saga for this purpose

How do I make an HTTP request in react-redux?

I am just getting started with react and I'm a bit lost. I'm trying to make a login page and make a http post request. Right now I'm just trying to get any type of HTTP request working, so I'm using request bin and I found this basic action in the docs for an npm package (https://www.npmjs.com/package/redux-react-fetch):
export function updateTicket(ticketId, type, value){
return {
type: 'updateArticle',
url: `http://requestb.in/1l9aqbo1`,
body: {
article_id: ticketId,
title: 'New Title'
},
then: 'updateTicketFinished'
}
}
So, after writing an action, what do I do? How do I actually get my app to call on and use that action? The docs for the npm package mention something about setting a state in my store, is that something I need to set up first?
You can try any of the following. I have used both fetch and axios they work amazingly well. Yet to try superagent.
For making requests you can either use fetch with
fetch-polyfill for compatibility across all browsers (link)
Axios library. (link)
Superagent with promises.(link)
If you use fetch you would need to use polyfill since it is not supported in IE and safari yet. But with polyfill it works pretty well. You can check out the links for how you can use them.
So what you would doing is in your action creator you can call an API using any of the above.
FETCH
function fetchData(){
const url = '//you url'
fetch(url)
.then((response) => {//next actions})
.catch((error) => {//throw error})
}
AXIOS
axios.get('//url')
.then(function (response) {
//dispatch action
})
.catch(function (error) {
// throw error
});
So that was for the API call, now coming to the state. In redux there is one state which handles your app. I would suggest you should go through redux basics which you can find here . So once your api call succeeds you need to update your state with the data.
Action to fetch data
function fetchData(){
return(dispatch,getState) =>{ //using redux-thunk here... do check it out
const url = '//you url'
fetch(url)
.then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array
.catch( error) => {//throw error}
}
}
Action to update state
function receiveData(data) {
return{
type: 'RECEIVE_DATA',
data
}
}
Reducer
function app(state = {},action) {
switch(action.types){
case 'RECEIVE_DATA':
Object.assign({},...state,{
action.data
}
})
default:
return state
}
}

Data fetching with React Native + Redux not working

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?

Resources