get data from promiseresult object of promise.all and axios call - reactjs

I am using the following code and my aim is to get the data from the data section of the PromiseResult object of the returned Promise. I am using the following code:
const promiseComment = axios.post(`${BASE_URL}/api/addComment/`, data, getDefaultHeaders());
let allPromises = []
allPromises.push(promiseComment)
Promise.all([allPromises])
.then(function (values) {
console.log(values[0][0]);
});
When I console the values, I get the following response, what I need is the data section from the response which I marked in the following image.
Thanks in advance

you need to resolve the promise inside
const promiseComment = axios.post(`${BASE_URL}/api/addComment/`, data, getDefaultHeaders());
let allPromises = []
allPromises.push(promiseComment)
Promise.all([allPromises])
.then(values=>values).then(obj=>console.log(object.data));

Related

How to use Axios.post() in a post request containing a json object request-body and a multipart form data (MP4)

Hi I Was wondering how I can send a a single axios post request containing a json object as the request body and also multipart form data (Mp4 file).
In my example I want to send 'details' and 'file'. I have tried sending details and file as 2nd and 3rd arguments to the axios.post() method but from what I can tell axios.post only accepts 2 args.
I have also tried appending the details and then the file, to the form data, but this does not work either.
If I split these into 2 seperate post calls, it works fine, but my application requires these to happen together.
I am getting the following error in my spring console:
[org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryqKyZ0R2SyFeDNCVp;charset=UTF-8' not supported]
Here is the error in my web dev tools console:
xhr.js:210 POST http://localhost:9191/api/123/file/upload 415
Id really appreciate any suggestions
const FileUpload = () => {
const [file, setFile]= useState(null)
const[details, setDetails] = useState({consent:false,
idConfirmed:false,
label:"",
roundId:""})
const changeHandler=(e)=>{
setFile(e.target.files[0]);
setDetails(prevDetails=>({
...prevDetails,
consent:true,
idConfirmed:true,
label:"test_Label"
}));
};
const handleSubmission=(e)=>{
e.preventDefault();
const data = new FormData();
data.append("file", file)
data.append("file", details)
console.log("Data: ", data)
axios.post(`${process.env.REACT_APP_URL_NEW_ROUND_VID}/123/file/upload`, data,
{
headers:{
"Content-Type":"multipart/form-data"
}
})
.then(res=>{
console.log("Data: ",res.data)
console.log("success")
})
.catch((e)=>{
console.log("Error", e)
})
//})
};
Here is my rest end point in Springboot:
#PostMapping(
path = "{patientId}/file/upload",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public void addWardRound(#PathVariable("patientId") String patientId,
#RequestParam("file") MultipartFile file,
#RequestBody WardRequest wardRequest){
WardRoundService.isFileEmpty(file);
WardRound round = service.saveRound(wardRequest);
String roundId = round.getRoundId();
service.uploadVid(patientId, roundId, file);
}
you can stringify and send the JSON data. but by using this method you need to parse it in the server!. it could be difficult
The best method is splitting it into 2 APIs
you can merge both API requests in UI by merging both APIs using promise.All
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
const promise1 = axios.get(URL1);
const promise2 = axios.post(URL2, data);
Promise.all([promise1, promise2]).then(function(values) {
console.log(values);
});
or else if you need to use the result of first API
then call the second API inside the response of first API itself

getting a value from a field in firebase

I am trying to retrieve a specific value of a field and store it inside a variable named joiningScore. This makes joiningScore a object with a promise that has a value in it. How can I get that value. I tried tucking in a .then method after the .get("currentPos") but it throws an error saying docSnapshot.get().then is not a function.
var joiningScore = positionDoc.get().then((docSnapshot) => { return docSnapshot.get("currentPos"); })
const positionDoc = frebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
here positionDoc is a reference to the document in firestore.
This is because you are assigning to a variable a Promise chain.
You need to wait that the Promise returned by the get() method is fulfilled in order to get the value. See this doc for more details.
So something along these line should work:
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
var joiningScore;
positionDoc.get().then((docSnapshot) => {
joiningScore = docSnapshot.get("currentPos");
})
You could also use an async function as follows:
async function getJoiningScore() {
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
const docSnapshot = await positionDoc.get();
return docSnapshot.get("currentPos");
}
Note that this function is itself asynchronous.

Where is fetched data saved in React?

I am trying to understand this snipped of code at an intrinsic level:
fetchAllData(){
fetch('http://ec2-x-x-xx-xx.xx-west-x.compute.amazonaws.com:3001/', {mode: "no-cors"})
.then(res => {
return res.json();
})
to better understand a simple component like this:
componentDidMount() {
this.fetchAllData();
}
fetchAllData(){
fetch('http://ecx-x-x-xxx-xx.xx-west-x.compute.amazonaws.com:3001/', {mode: "no-cors"})
.then(res => {
return res.json();
})
.then(resJson => {
this.setState(prevState => {
return{
fetchDataLoaded: true,
fetchData: resJson.data.todolist,
};
});
});
}
When fetching from an API, is the data stored temporarily in the res
=> function and chained on using .then?
If so, how could I visualise (in the console maybe?) the properties of the data fetched?
I find myself in a position where I need to manipulate data pulled from an API I don't know the shape of.
I am new to React and any detailed explanation would help a lot, thank you.
This isn't a react thing at all, but rather plain javascript and promises. fetch returns a resolved promise. The response isn't "saved" in res, per se, but rather is passed to a function where you've named the parameter res. If you want to view the raw response res you can do that in the first chained then, ensuring you still return the json promise for the next thenable.
fetch('http://ec2-3-8-196-93.eu-west-2.compute.amazonaws.com:3001/', {mode: "no-cors"})
.then(res => {
console.log('res', res);
return res.json();
})
Perhaps it would be a little clearer broken down a bit. Factor out the anonymous inline function into a named one, and pass that as the thenable callback. The fetch result isn't really saved anywhere (it is technically in memory in the browser heap, but that's another topic) and is just being passed to a function.
const logResultAndReturnJson = result => {
console.log('result', result);
return result.json();
};
fetch('http://ec2-3-8-196-93.eu-west-2.compute.amazonaws.com:3001/', {mode: "no-cors"})
.then(logResultAndReturnJson)
If you need to manipulate the fetched data, then you likely want to look at the resolved JSON object and not the response object.
In the given example, the variable resJson contains the response body parsed by JSON(i.e. this piece of code only works if the API returns a JSON response).
Adding on to #drew, This .then(...).then(...) is called Promise Chaining. It is a useful way of making a flow where you can process data in stages and then deal with errors in the end.
As Reference, these two pages will surely help
promise-basics
promise-chaining

React native is not creating the link properly for searching

I am performing the search functionality in react native but i am getting an issue with sending the array of locations in link. My link is looking like this...
https://....listing/get_freelancers?listing_type=search&location=australia,england,united-emirates,united-kingdom
This is what i am getting comma seprated values in my link but i need this type of URL..
http://...search-freelancers/?keyword=&location%5B%5D=australia&location%5B%5D=canada
In this URL i have Array of locations i don't want comma separated values i need URL like this... here is my code where i am passing array in my URL...
fetchFreelancerData = async () => {
const { params } = this.props.navigation.state;
const response = await fetch(
BaseUrl+"listing/get_freelancers?
listing_type=search&location="+params.projectLocationKnown
);
const json = await response.json();
this.setState({ fetchFreelancer: json });
console.log( params.projectLocationKnown );
console.log( BaseUrl+"listing/get_freelancers?listing_type=search&profile_id=&keyword="+params.title+"&skills="+params.SkillsKnown+"&location="+params.projectLocationKnown+"&type="+params.freelancerLevelKnown+"&english_level="+params.englishKnown+"&language="+params.LangKnown );
};
In this patch of code i am getting values from another component and passing these array values in my fetch call here... please help about how to make the URL properly to fetch response.
You can try using encodeURIComponent(url) where url is the string containing the url you need to convert

Find Object Array and its Properties from Ajax Post Request

I'm sending an AJAX request to an internal PHP and receiving back an object. The object has properties of "data" and "status", yet when I try to access them, it does not return anything. How can I show each property separately?
For reference, the returned obj array is:
{"data:[{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}]
function GetAll() {
var PostRequest ={};
PostRequest['tagId']= 'all';
$.post('php here',PostRequest,ShowAllTags);
}
function ShowAllTags( responseData, responseStatus ) {
console.log(responseStatus);
var tagData = {};
tagData = responseData;
console.log(tagData['data']);
}
So according to the above comment mention by me, The problem is with json object, in response.
So first of all fix that,
Generic solution of this problem will be;
var obj = [{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}];
obj.forEach(function(value, index){console.log(value.tagId)});
This might help, how to get value of each property

Resources