React-Native : How to get callback of api call in another class - reactjs

I am calling a web service
Here is my code:
var result;
export function callPostApi(urlStr, params)
{
fetch(urlStr, {method: "POST", headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => { console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
})
.done();
return result
}
I am calling from here:
callapi(){
var dict = {
email: 'at#gmail.com',
password: '123456',
}
result = callPostApi('http://demo.com', dict)
}
Currently, it is calling in Async mode that we want but code is written below this method getting execute immediately after calling of above method
i want callback when result from sever has received so that i can execute code written below the above method is execute after receiving response from server.

You need to use Promises.
Change your callPostApi function to return a Promise, then you can chain additional then, catch and finally calls.
export function callPostApi(urlStr, params) {
return fetch(urlStr, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
callapi() {
callPostApi('http://demo.com', {
email: 'at#gmail.com',
password: '123456',
})
.then((response) => {
// Continue your code here...
});
}

Related

React Native How to filter sectionlist data on the basis of id

this is the get api of sectionlist data
const getAllMatches = async () => {
await fetch(APIS?.Matches, {
method: 'GET',
headers: {
Authorization: user,
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(({matches}) => {
setAllMatches(matches);
})
.catch(error => {
return console.error(error);
});
};
just in your code when setting matches use:
setAllMatches(matches.filter((item,index)=>item.category=="fruits");
in this case we are putting matches with the category fruits, you can adjust accordingly

Cannot get componentDidMount() to update empty array via this.setState with fetched JSON data

I have an empty array declared as such:
class EditPlaylistDetails extends Component {
constructor(props) {
super(props);
this.state = {
allPlaylists: []
}
};
And my ComponentDidMount() is:
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).then((res) => {
this.setState({
allPlaylists: res
},
() => console.log(this.state.allPlaylists));
})
};
Two problems:
#1) When I try to call upon this fetched data via a .map function, it comes back as "undefined".
#2) The '() => console.log(this.state.allPlaylists))' code snippet doesn't even fire off at all. It doesn't attempt to execute the console.log.
I am able to console.log(res) within that snippet of code and it displays the updated allPlaylists array with all of the info without issue.
Add return to the second promise handler
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {
console.log(res);
return res;
}).then((res) => {
this.setState({
allPlaylists: res
},
() => console.log(this.state.allPlaylists));
})
};
For one of my projects, removing the { before this.setState( worked.
componentDidMount() {
fetch('http://localhost:5040/playlist/', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': this.props.sessionToken
})
}).then((response) => response.json())
.then((res) => {console.log(res);})
.then((res) => this.setState({allPlaylists: res})};

Unhandled Rejection (TypeError): Cannot read property 'error' of undefined

I'm fairly new to React and I've been trying to create a SignUp page, however, I'm stuck in this error. Can someone give me any indication on what I should do in order to solve this error?
Signup Method:
// = Action =
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
Rewrite Signup method (ps: I only changed the .catch handler)
`
// Sign up
export const signup = user => {
return fetch(
`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err =>
console.log(err));
return err;
}
`
You need to wrap up your fetch logic inside a Promise to return a value to the caller.
export const signup = user => {
return new Promise((resolve, reject) => {
fetch(`${API}/signup`,
{
method: 'POST',
headers: {
Accept:'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(jsonData => resolve(jsonData))
.catch(err => resolve({error: `something went wrong err : ${err}`}));
})
}
signup(user).then(data => {
if (data.error) {
// handle error case
} else {
// handle success case
}
})
Now your signup method will return a value. Your data variable won't be undefined anymore.
I hope it helps, feel free to add comments or ask me more details

How to make common API call function using fetch

I am trying to make common function which will handle all of my API calls from anywhere
I am using react": "^16.8.6" and fetch for making api call
So far what i have figure out to do
is
Helper.js
export function ApiHelper(url, data = {}, method = 'POST') {
let bearer = 'Bearer ' + localStorage.getItem('user_token');
var promise = fetch(url, {
method: method,
withCredentials: true,
// credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'chaptoken',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
},
(error) => {
error = error;
}
)
}
export function AnyOtherHelper() {
return 'i am from helper function';
}
And here is from where i am calling this function
componentDidMount() {
let url = `http://localhost/project/api/getdata`;
let op = ApiHelper(url);
}
when I console result in then i am getting appropriate result but what i want to return that response how can i do this part is troubling me
Even i have try to store the result in global variable and it is not working.
Also i have to return the response only when promise is resolved.
You are making an async call from your helper function which means, you will have to return promise from your helper function like this -
export function ApiHelper(url, data = {}, method = 'POST') {
let bearer = 'Bearer ' + localStorage.getItem('user_token');
return fetch(url, { // Return promise
method: method,
withCredentials: true,
// credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'chaptoken',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then((result) => {
console.log(result);
return result;
}, (error) => {
error = error;
})
}
USAGE
componentDidMount() {
let url = `http://localhost/project/api/getdata`;
ApiHelper(url)
.then(resposnse => {
console.log(resposnse);
});
}

Api call works on postman but Doenst work on my code

So I have to update some user info ,it works fine on postman but when I try to type it in react-native I must be doing something wrong in the body of the fetch method. In postman I set x-www-form-urlencoded and type the keys like this :
Key ----- Value
moto ----- test
and that seems to work,but when I try to do the same on my code I somehow fail at it,here is my code
updateUser(){
return fetch(url,{
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type":"application/x-www-form-urlencoded"
},
body: JSON.stringify({
moto: this.state.moto
}
})
}
)
I get 200 response which means the call works but I must be seting the parameter moto wrong somehow.
Any ideas ?
"Content-Type":"application/x-www-form-urlencoded"
should be
"Content-Type":"application/json"
form-urlencoded is way different from your body: JSON.stringify().
You'll want to use a FormData object instead:
const body = new FormData();
body.append('moto', this.state.moto);
fetch(url, {
method: "PATCH",
headers: {
"X-Auth-Token": bearerToken,
"Content-Type": "application/x-www-form-urlencoded"
},
body,
})
APICall = () => {
fetch(‘Your http URL’, {
method: 'PATCH',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
‘X-Auth-Token’: bearerToken,
},
body: JSON.stringify({
moto: this.state.moto
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.statuscode == 1) {
Alert.alert('Success');
} else {
Alert.alert(responseJson.message);
}
}).catch((error) => {
console.error(error);
});
}
finally fixed it by seting body to
body:
`moto=${this.state.moto}`
it appears that urlencoded headers require parameters in the form of
parameter1=value1&parameter2=value2
componentDidMount() {
return fetch(“Your URL”, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"Authorization": “token”
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
})
.then((response) => response.json())
.then(function (data) {
alert(“Success”)
console.log('Request succeeded with JSON response', data);
})
.catch(function (error) {
alert("error occur")
console.log('Request failed', error);
});
}
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})

Resources