React native fetch url endcoded - reactjs

Does anyone know what the problem is with the below code? Because currently i can get only 1 data from the db but when the db has 2 data or 3 data then it will show the following error message:
JSON Parse error : Unable to parse JSON String
componentDidMount(){
const packid = 'this.props.navigation.getParam'('packid');
return fetch('http://xxx.xxx.x.xxx/User_Project/packages_List_klcc.php?packid='+packid, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
this.setState({
isLoading: false,
dataklcc: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}

Related

How to send a image jpg/png file from react to express server

I am trying to send an object from react to express server using node.js
this is my object:
const formData = {
location: location,
cost: cost,
email: email,
image: image,
};
This is my fetch post method :
fetch("http://localhost:5000/places", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(formData),
})
.then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
I can see the image file object in client site console but I am not getting that in expreess server.
You have to send your input data as FormData to share images/files to the backend.
function uploadImage() {
let formData = new FormData(yourFormData);
fetch("http://localhost:5000/places", {
method: "POST",
body: formData,
}).then((res) => res.json())
.then((data) => {
if (data.insertedId) {
alert("Plcae added successfully");
}
})
.catch((error) => {
console.error("Error:", error);
});
}

ReactJS: post request with data through fetch

In my app component, I have state features that contains an array(1500) of arrays(9). I want to send the state (or large array) to my backend so I can run my model and return labels with the following function:
const getLabels = (model) => {
fetch('/spotify/get-labels', {headers: {
'model': model,
'features': features
}})
.then(response => response.json())
.then(data => setLabels(data))
}
However, the response has status 431. This was kinda expected, but I'm not sure how to transmit the data to my backend efficiently. Maybe convert it to json and then put in the headers of my request?
You can try something like this with fetch:
fetch('/spotify/get-labels', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ model, features }),
})
.then((response) => response.json())
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
or with axios
axios
.post('/spotify/get-labels', { model, features })
.then((data) => {
// Boom!
})
.catch((error) => {
// An error happened!
});
As far as I'm understanding your concern, I guess passing the 'model': model,'features': features in body should work.
Or using Axios, you can make the request. It exactly like Axios but far better
axios({
url: '/spotify/get-labels',
method: "post",
data: {
'model': model,
'features': features
},
})
.then((response) => response.json())
.then(data => setLabels(data))
.catch((error) => {
console.log("error : ", JSON.parse(error));
});

When I fetch(url).then(console.log), the console.log does not execute

Hi I've been in a limbo with the problem. I'm trying to use the update method to update the iterations of clicks in my URL shortener project. The iterations update in the DB but then it isn't reflecting on the front end. I was thinking it would update in the then() function after fetching but then it seems like it didn't go in the then() function. My question is that is there something wrong with the code or is there an alternative way for it to get to the then()?
Client side (React)
const id = record._id;
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Server side (Mongoose)
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
});
Your server isnt making a response after getting the request from the client so the connection is pretty much in limbo for lack of a better word.
You need to send a response to client
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
res.status(200).json({
message: updateURL
})
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(500).json({
message: err.message
})
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(200).json({
message: err.message
})
});
});
Btw, with fetch you need to add two thens to get the data you want.
But in your case you don't want to get the data so one would do
So something like this
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then(response => response.json())
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Also you should actually add the backend link as a proxy value to your package.json as a better way of making the API call to the backend.
"name": "",
"version": "",
"main": "",
"proxy": "http://localhost:3001", //note the proxy
"license": "",
....
Then you just need to do this with fetch
fetch(`/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})

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

React Native refreshing data

I'm trying to refresh some data when users re-vistis the screen. The way im using other places and it works. but can't figure out why this won't fly on this screen?
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this.handleDidFocus)
}
async handleDidFocus() {
...
}
This is how I load data the first time and want to load it again when users revisits.
componentWillMount() {
this.getGroupAccepted();
}
async getGroupAccepted() {
if (this.state.token == null) {
var token = await AsyncStorage.getItem("token");
this.setState({ "token": token });
}
fetch('https://.../api/group/getActive', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: this.state.token
})
})
.then(response => response.json())
.then((data) => {
this.setState({
groups_accepted: data.groups_active,
loading: false,
});
})
.catch((error) => {
console.error(error);
});
}
This is what worked. Now when a user revisits the screen it loads the data once again.
componentDidMount = () => {
this.props.navigation.addListener('didFocus', this._handleDataChange)
}
_handleDataChange = () => {
this.getGroupAccepted();
}

Resources