How to use Promise.All in react-native - react-native

I use promise.All to wait finish methods before render component.
I used like this :
constructor(props) {
super(props);
this.controllAll();
}
controllAll() {
Promise.all([this.callFetch()])
.then(([fetchResponse]) => {
console.log('finished', fetchResponse);
})
.catch(err => {
console.log('Mistake:', err);
});
}
callFetch() {
fetch('url', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json', // <-- Specifying the Content-Type
}),
})
.then((response) => response.text())
.then(leaders => {
this.PutImagesToObject(leaders );
});
}
I want to wait to finish callfetch() method finish before render Component. But when I run, firstly in debug mode I see 'finished'.
Doesnt have to wait to finish CallFetch() method to show me 'finished'

Try to add return statement
callFetch() {
return fetch('url', {
...

Related

How do I use Async Storage to save Data Locally after calling fetch in react native?

I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

Why doesn't fetch work in store's nuxtServerInit?

For my project I'm using Nuxt. In the store's action I have this piece of code:
async nuxtServerInit({ commit }) {
this.dispatch('fetchAllClients')
},
async fetchAllClients({ commit, state }) {
console.log('fetch clients')
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
So, on Nuxt init I would like some fetches to be run, so it can update some states (this is done in de storeClients() which is committed in the fetch). If I copy the fetchAllClients() method inside the nuxtServerInit() then everything works just fine.
async nuxtServerInit({ commit }) {
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
But when I call a separate method as shown in the code above, then fetch won't work. The log is shown, so the method is called properly. But somehow the fetch doesn't do anything. What am I doing wrong?
You should have this instead
async nuxtServerInit({ dispatch }) {
await dispatch('fetchAllClients')
}

How to get Html code by fetching web API response?

When we are trying to fetch html code via fetch API response but we are enable to get it because it return "Unexpected Token <"
onLoginService2 = async () => {
try {
var hittingURl = "https://members.iracing.com/membersite/Login?username=dave#rms55.com.au&password=rms55Pa55&utcoffset=-600&todaysdate=1558055491688&checkbox=0";
const myRequest = new Request(hittingURl.toString(),
{
method: 'POST',
headers: {
'Accept': 'text/html',
'Content-Type': 'text/html;charset=ISO-8859-1',
},
timeout: 1000,
// body: JSON.stringify("")
}
);
fetch(myRequest)
.then((response) => console.log("abcdefghijklmon--> "+JSON.stringify(response)))
.then((data) => {
console.log("RESPONSERR----> ",data+"");
// this.setState({ isLoading: false })
// this.onLoginSuccessFull(responseJson)
})
.catch((error) => {
this.setState({ isLoading: false })
console.log("response--31" + error);
})
} catch{
}
// }
}
The response of first then has a method .text(), which return Promise
Try this
fetch(myRequest)
.then(resp => resp.text())
.then(text => {
//text is html
})
*Just copy the above and run in console to see the result.

React Native: API is not calling on 2nd time(fetch/axios)

I am creating react-native app using fetch method to get the data from API but when I am build the app(remove and install new app) that time it is calling API called but on 2nd time it is not.
I have also uses
componentDidMount, componentWillMount
but not work for me. following is my code:
export default test extends Component{
_isMounted = false;
constructor(props){
super(props);
this.state = {
showList:[]
}
}
componentDidMount() {
let currentComponent = this;
currentComponent._isMounted = true;
fetch(API_URL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => { return response.json()})
.then((responseJson) => {
console.warn("responseJson: ", responseJson);
if(currentComponent._isMounted){
currentComponent.setState({showList: responseJson.data});
}
})
.catch((error) => {
console.error(error);
});
}
componentWillUnmount(){
this._isMounted = false
}
}
I have add full code here. this is only called on first time, after that it will get only from cache(I think).Please help me.
Thanks
I'd look into the onEnter hook on your scene using react-native-router-flux.
Something like this should work:
class Test extends Component {
static onEnter() {
fetch(API_URL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => { return response.json()})
.then((responseJson) => {
console.warn("responseJson: ", responseJson)
if (currentComponent._isMounted) {
currentComponent.setState({ showList: responseJson.data })
}
})
.catch((error) => {
console.error(error)
})
}
}
(if you need to access this in the method, here is an idea)

React-Native: Keyboard runs slow when even on real device

Every time my app runs the keyborad seems to run slower than expected, i have a recursive call that updates an alert every 500 milli-seconds but is this why the keyboard is running slow when typing or is this a seperate issue. I dont have code to show you as everything else in the app runs fast apart from the keyboard. I have js dev mode disabled aswel.
Any clues?
<AutoGrowingTextInput underlineColorAndroid="transparent" style={{flex:1}}
maxHeight={200}
minHeight={45}
placeholder="Message..."
style={{backgroundColor:'#ffffff',}}
onChangeText={(message) => this.setState({message})}
value={this.state.message}
/>
getLatestMessagesRecurse = () =>{
return fetch('http://example.com/example.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
example: example,
example: example
}),
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson != false){
this.setState({_messageAlert: true});
}else{
this.setState({_messageAlert: false});
}
})
.catch((error) => {
alert(error);
});
}
componentDidMount() {
this._interval = setInterval(() => {
this.recurse();
}, 500);
}
recurse = () => {
this.getLatestMessagesRecurse();
}
componentWillUnmount() {
clearInterval(this._interval);
}