I'm able to fetch messages from the API and render them in the component successfully. However, as the number of messages increases, fetching from the API causes the app to freeze and clicking any event (such as selecting a different tab or button) will be only triggered when the request is done.
I've read about using next-frame to solve this issue but I'm finding difficulties in how to add it to my code. I'd like to know how to implement next-frame inside it.
This is the section of code that fetches messages from the backend:
componentWillMount()
{
/**load user's messages */
loadmessages() {
fetch(server + 'view_user_messages.php', {
method: 'POST',
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain',
},
body: JSON.stringify({
user_idDB: modulevariables.globaluserid
})
}).then((response) => response.text())
.then((responseJson) => {
var jsonconvertedrows = JSON.parse(responseJson)
this.setState({ messagestable: jsonconvertedrows })
}).catch((error) => {
console.log(error);
})
}
}
Related
I am working on creating a user in Shopify by using the Admin and Storefront API build in my Next.js project. The user inputs an email and clicks "Sign up" which sends a post fetch request to my Next.js middleware. The post request fails and never sends back a response and the browser tab continuously circles like it is loading. Here is the API call belo. Why is it that the network tab of the inspector states "Pending"? I Thought .then() resolves a promise. Thank you for any help in advance.
export default function login(req: NextApiRequest, res: NextApiResponse) {
var myHeaders = new Headers()
myHeaders.append('Access-Control-Allow-Origin', '*')
myHeaders.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
myHeaders.append('Access-Control-Allow-Headers', 'Content-Type')
myHeaders.append('Content-Type', 'application/json')
myHeaders.append('Authorization', `${secretToken}`)
var raw = JSON.stringify({
customer: {
email: email,
accepts_marketing: true,
verified_email: true,
},
})
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
}
fetch('https://xxxxxxxxx.myshopify.com/admin/api/2022-10/customers.json', requestOptions)
.then((response) => response.text())
.then((result) => {
console.log("result - ",result)
res.status(200);
}).finally(() => {
console.log("Done")
})
.catch((error) => console.log('error', error))
"CAUTION: request is not finished yet"
`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`
I've recently started learning some backend and I'm having some issues with creating a delete function. I'm using Vue with Node, Express, Monk/Mongo.
I have a page where these card components are dynamically posted to. However,every time I run that said delete method to remove one specific instance of that said component in that view, I keep getting this error message:
DELETE http://localhost:1234/tips 500 (Internal Server Error)
And this is what I see in the Network Logs:
message: ""value" must be of type object"
And on my index.js: (sidenote, when I pass '/tips' to app.delete and run tips.remove(req.body) instead of tips.findByIdAndRemove... I end up deleting all instances of that component in that view.
app.delete('/:id', (req, res) => {
console.log(req.body);
tips.remove(req.params.id).then((tip) => {
res.json(tip);
}).catch((error) => {
res.status(500);
res.json(error);
});
});
And this is what I have on my vue component that has the delete method:
const API_URL = 'http://localhost:1234/tips'
methods: {
deleteMyTip(){
fetch(API_URL, {
method: 'DELETE',
body: JSON.stringify(this.tipObject),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => response.json()).then(result => {
console.log(result);
});
}
}
You're trying to pass a tip object as the request body, but DELETE requests aren't supposed to have any body. Your DELETE route is expecting an ID, all you need to do is pass the ID of the tip you want to delete in the URL.
deleteMyTip(){
fetch(`${API_URL}/${this.tipObject.id}`, {
method: 'DELETE',
})
.then(response => {
// Remove item from UI
});
}
It's also common practice to return an empty body with a 204 (no content) status.
I'm building an app using React Native with Expo and an ASP.Net Web API.
I'm using two computers: one I published the Web API on it and using it as a server which has the IP 192.168.1.9 ,
and the other one with IP 192.168.1.6 I'm using for developing.
The problem is when I ping the server computer I get a reply and when I use postman I get the data I requested,
but when I run the app using Expo on my Android Phone, the request enters the catch and returns an error.
Here is the code:
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
})
.then(response => { response.json(); })
.then(users => {
this.setState({ allUsers: users });
})
.catch(error => console.error('Error getting users :: ', error));
I have tried everything I could possibly think of, but no use.
Can someone tell me what the problem is? thank you .
You can configure Accept and Content-Type of headers.
And get the correct value for the object.
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then(res => {
this.setState({ allUsers: res.Username });
})
.catch(error => console.error('Error getting users :: ', error));
I'm facing an issue while using react native fetch api. many times request got failure . I have a high speed connection. but many times it got failed.
that issue is happening In android,ios both.
const shoppingApi = 'myserverlink';
async function Sendshoppinapi(data) {
try {
let response = await fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
});
let responseJson = await response.json();
return responseJson;
}
catch (error) {
Alert.alert(error.toString())
}
}
export {Sendshoppinapi};
data that I sending server as post request
add_to_wishlist = (item,index) => {
{
let data = new FormData();
data.append('methodName', 'add_to_wishlist');
data.append('user_id', global.userid)
data.append('item_id', this.props.navigation.state.params.itemid.toString())
Sendshoppinapi(data).then((responseJson)=>{
console.warn(responseJson);
if(responseJson.responseCode == '200'){
this.setState({fav:false})
Alert.alert('SHOPPING','Item added to wishlist successfully.',[{text: 'OK',},],{ cancelable: false })
}
else{
this.setState({fav:false})
Alert.alert('SHOPPING','Item already .',[{text: 'OK',},],{ cancelable: false })
}
})}
}
Error that when request got failed
I've quoted an answer I used for another post - however I have added await.
You can check the status of the call, to determine perhaps why the network call failed. Try using fetch's ok to check whether the response was valid, for example:
.then(function(response) {
if (!response.ok) {
//throw error
} else {
//valid response
}
})
Using await:
let response = await fetch(url)
if (response.ok) return await response.json()
You can also access the response's status like:
response.status;
or also, statusText such as:
response.statusText;
checkout the below:
https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText
https://developer.mozilla.org/en-US/docs/Web/API/Response/status
https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
Use then() function with promises. (Requested code snippet)
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json()
})
.then((resp) => {
//resp contains your json data
});
You also can make your function returns a Promise, and use it with then():
function sendShoppingApi(data) {
return new Promise((resolve, reject) => {
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json();
})
.then((resp) => {
resolve(resp);
/*
you should also check if data is valid, if something went wrong
you can reject the promise:
if(!dataOK)
reject("error message");
*/
});
});
}
So now you can do something like this:
sendShoppingApi(data)
.then((resp) => {
//do stuff with your data
})
.catch((err) => {
//handle error
});
UPDATE
could be a duplicate of this: React Native fetch() Network Request Failed
For the case when you are running the app on the android device, the API is on a computer and both of them are on the same network I have added some possible things to check. I haven't detailed specific solutions since there are many answers on each topic.
Do a quick check with ngrok https://ngrok.com/ on the free plan to see if that works. If yes:
Make sure the API is accessible by trying to access it on the device browser (most important is to check if you allow the port at inbound rules, firewall).
If you are using HTTPS, you might get an error if your react native env is not properly configured to accept not trusted certificates, assuming you are using a non trusted one. Do a check without HTTPS, only with HTTP, to see if it's the case. https://github.com/facebook/react-native/issues/20488