How to send data with fetch in react-redux - reactjs

I'm doing a multiple checkbox filter, and I have to send to the server an object with a post method. How can I use fetch to do that? Can I send data using fetch? And from the server I have to receive a filtered list.
Thank you!

Yes you can specify the fetch method with 'POST'
example code here from https://facebook.github.io/react-native/docs/network.html
function getMoviesFromApiAsync() {
return fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson.success;
})
.catch((error) => {
console.error(error);
});
}

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

Api request with some data in reactjs

In my project the API requires some data to be passed that is :
Bearer Token
Body - {email: [email_address]} e.g. {email: “mayank#gmail.com”}
Params - Your name i.e https://1234.amazonaws.com/alphabet/mayank
I am doing this in reactjs.
But I am confused how to use params.
My try:
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
};
fetch('https://1234.amazonaws.com/alphabet/mayank')
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},
But this is not working.
You should provide your parameters to the fetch request in an object like this. Read more about how to make post requests here.
fetch('https://1234.amazonaws.com/alphabet/mayank',
{
method: 'POST',
headers: {
'Authorization': 'Bearer abcd',
},
body: JSON.stringify({
email: 'mayank#gmail.com'
})
})
.then(res => res.json())
.then((data) => {
this.setState({
data: data,
});
},

Axios response showing status code 200 but no response data

I'm a newbie to axios. I'm trying to send a post request with an authorization header. The response data is returned in Post man. But I couldn't see any response data in my browser. Please help.
axios.post('http://13.127.3.151:8080/v1/dashboard/getuserdetails', {
utype: "staff",
uemail: "abdulwahidnasir#bitsathy.ac.in"
},
{ headers: { 'Authorization': `Bearer ${serviceToken}`,
'Content-Type': 'multipart/form-data' } })
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response)
});
I have found the problem, it was with formData. This works fine now.
let formData = new FormData();
formData.append("utype", userType);
formData.append("uemail", email);
axios.post('http://13.127.3.151:8080/v1/dashboard/getuserdetails', formData,
{ headers: { 'Authorization': `Bearer ${serviceToken}`,
'Content-Type': 'multipart/form-data' } })
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response)
});

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);
})

Sending an array to a server to fetch some data with React Native

I am trying to do fetch a data from the server with given datas. I am using the following code :
const details = {
'function': 'getUsers',
};
const formBody =
Object.keys(details).map(key=>encodeURIComponent(key)+
'='+encodeURIComponent(details[key])).join('&');
console.log(formBody);
fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': 'XPIDER_SID=' + this.props.text
},
body: formBody
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === 'okay') {
this.setState({ users: responseJson.users });
} else {
this.setState({ error: responseJson.error });
}
})
It works great until now. Now I have to send a array of datas but when I write an array in details constant, the server does not take the array because of the formBody. In formBody, the whole request is string, so the array converted to a string. How can I send a array with this ? or do you guys know any other option ? Thank You !
Send your array as JSON like this:
body: JSON.stringify(your_array)
Then deserialize it on the server

Resources