Axios.put inside Axios.get - javascript

I want to update status, but when I want to do the 'put' it's not working cause axios in axios.put is not define. Can you help me please.
getAbsencesByRequestId(reqId) {
axios.get(REQUESTID_URL + reqId).then(response => {
this.collaboId = response.data[0].collabId;
this.beginDate = response.data[0].startDate;
this.finishDate = response.data[0].endDate;
this.reason = response.data[0].type;
}, (error) => {
console.log(error.response.status)
}) axios.put(REQUEST_URL + reqId, {
collabId: this.collaboId,
startDate: this.beginDate,
endDate: this.finishDate,
status: 'VALIDATED',
type: this.reason
})
},

You should manage properly the order of your requests
axios.get(url /*optional payload and headers*/).then((getResponse) => {
//do GET stuff with response
}).then(() => {
//do PUT call
axios.put(url, /*optional payload and headers*/).then((putResponse) => {
//do PUT stuff with response
})
}).catch((e) => {
//handle the error
})

Related

Return Response When First request failed And Try In Second Request

I try to explain the problem.in App.js I have Function getUser .when call this function.in first request get 401 error . For this reason in axios.interceptors.response I receive error 401.At this time, I receive a token and repeat my request again.And it is done successfully.But not return response in Function getUser.
I have hook for authentication and send request.
import React from "react";
import axios from "axios";
const API_URL = "http://127.0.0.1:4000/api/";
function useJWT() {
axios.interceptors.request.use(
(request) => {
request.headers.common["Accept"] = "application/json";
console.log("request Send ");
return request;
},
(error) => {
return Promise.reject(error);
}
);
axios.interceptors.response.use(
(response) => {
console.log("answer = ", response);
return response;
},
(error) => {
if (error?.response?.status) {
switch (error.response.status) {
case 401:
refreshToken().then((responseTwo) => {
return
sendPostRequest(
error.response.config.url
.split("/")
.findLast((item) => true)
.toString(),
error.response.config.data
);
});
break;
case 500:
// Actions for Error 500
throw error;
default:
console.error("from hook interceptor => ", error);
throw error;
}
} else {
// Occurs for axios error.message = 'Network Error'
throw error;
}
}
);
const refreshToken = () => {
const token = localStorage.getItem("refresh");
return axios
.post(API_URL + "token", {
token,
})
.then((response) => {
if (response.data.access) {
localStorage.setItem("access", response.data.access);
}
if (response.data.refresh) {
localStorage.setItem("refresh", response.data.refresh);
}
return response.data;
});
};
function login(email, password) {
return axios
.post(API_URL + "login", {
email,
password,
})
.then((response) => {
if (response.data.access) {
localStorage.setItem("access", response.data.access);
}
if (response.data.refresh) {
localStorage.setItem("refresh", response.data.refresh);
}
return response.data;
});
}
const sendPostRequest = (url, data) => {
console.log(300);
const token = localStorage.getItem("access");
axios.defaults.headers.common["jwt"] = token;
return axios.post(API_URL + url, {
data,
});
};
const logout = () => {
const token = localStorage.getItem("refresh");
return axios
.delete(API_URL + "logout", {
token,
})
.then((response) => {
localStorage.removeItem("access");
localStorage.removeItem("refresh");
});
};
return {
login,
logout,
refreshToken,
sendPostRequest,
};
}
export default useJWT;
In App.js ,I want to repeat the same request again if a 401 error is issued when I read the user information.
The request is successfully repeated but does not return the value.
When first request fail response is return equals null . and in catch when receive 401 error i am send second request but not return response.
I send request below code .
const getUser = () => {
console.log(12);
return sendPostRequest("user");
};
useEffect(() => {
let token = localStorage.getItem("access");
console.log("token = ", token);
if (token != null) {
//Here I have done simulation for 401 error
localStorage.setItem("access", "");
getUser()
.then((response) => {
console.log("response 1= ", response);
})
.catch((exception) => {
console.log("exception = ", exception.toString());
})
.then((response) => {
console.log("response 2= ", response);
});
} else {
navigate("/login");
}
}, []);
Best regards.
I didn't fully understand what exactly you want to do here.
But if you are looking to retry when 401 happens, you could use axios-retry to do it for you.
I'll pass the basics, but you can look more into what this does.
// First you need to create an axios instance
const axiosClient = axios.create({
baseURL: 'API_URL',
// not needed
timeout: 30000
});
// Then you need to add this to the axiosRetry lib
axiosRetry(axiosClient, {
retries: 3,
// Doesn't need to be this, it can be a number in ms
retryDelay: axiosRetry.exponentialDelay,
retryCondition: (error) => {
// You could do this way or try to implement your own
return error.response.status > 400
// something like this works too.
// error.response.status === 401 || error.response.status >= 500;
}
});
Just like in your code, we need to use interceptors if you want to avoid breaking your page, otherwise you can use try catch to catch any errors that may happen in a request.
// It could be something like this, like I said, it's not really needed.
axiosClient.interceptors.response.use(
(success) => success,
(err) => err
);
And finally, you could use the axiosClient directly since it now has your API_URL, calling it like this axiosClient.post('/user').
More or less that's it, you should just debug this code and see what is causing the return value to be null.
I would change these then/catch to be an async/await function, it would be more readable making your debugging easier.
axios-retry example if you didn't understand my explanation.
I find anwser for this question.
When error 401 occurs then create new Promise
I Wrote this code.
case 401:
return new Promise((resolve, reject) => {
refreshToken().then((responseTwo) => {
resolve(
sendPostRequest(
error.response.config.url
.split("/")
.findLast((item) => true)
.toString(),
error.response.config.data
)
);
});
});

How post requests get header parameter

Backend services are working correctly. I'm trying to set the header parameter. But I am making a mistake somewhere. I can't get a response.
Error appearing in console: Request failed with status code 417
How can I solve it?
PolicyService.js
const getAsosPaymentInfo = (getPolicyAccountInfoRequestDto) => {
return new Observable((observer) => { // <PaymentInfoResponseDto>
axiosInstance
.post(SERVICE_PATH + '/getAsosPaymentInfo', getPolicyAccountInfoRequestDto, {
headers: { 'sales-channel': 200008, 'agency-code': 10038, 'content-type': 'application/json' }
})
.then((response) => {
observer.next(response.data);
observer.complete();
})
.catch((err) => {
console.log(err);
});
});
};
policy-payment-info.js
const req = {
policyNumber: '1277976920',
renewalNumber: '01',
policyTypeExtCode: '800',
productTypeExtCode: '2000062'
};
useEffect(() => {
if (props.location.state.policy.isActive === true) {
PolicyService.getAsosPaymentInfo(req).subscribe(
(response) => {
console.log(response);
}
);
}
}, []);

React: POST Fetch request to JSON server results in TypeError: Cannot read property 'id' of undefined

I am trying to wright an object to a db file using JSON server; however, the JSON server keeps giving the error: TypeError: Cannot read property 'id' of undefined.
I can successfully read for the file using Fetch, its just POST that I'm having this trouble with. Any ideas?
//this is the function where I perform the POST
const handleSubmit = (e) => {
e.preventDefault();
setSubmitted('t');
setIsPending(true);
const arg = { filename, trialId, hash, location, author, submitted };
fetch('http://localhost:8000/args/', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(arg)
}).then(() => {
console.log('new file added');
})
};
//This is my current db file:
{
"args": [
{
"filename": "Accelerometer",
"trialId": "01",
"hash":"",
"author": "",
"location": "IPFS",
"submitted": "f"
}
]
}
// This is my fetch that works that I use to read from the db page.
setTimeout(() => {
fetch('http://localhost:8000/args', { signal: abortCont.signal })
.then(res => {
//check response for error
if (!res.ok) {
throw Error('Error when fetching data');
}
return res.json();
})
.then(data => {
setArgs(data);
setIsPending(false);
setError(null);
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted');
} else {
setError(err.message);
setIsPending(false);
}
})
}, 1500);
// This is the function Function.createID in the server that seems to be having an issue.
function createId(coll) {
const _ = this;
const idProperty = _.__id();
if (_.isEmpty(coll)) {
return 1;
} else {
let id = _(coll).maxBy(idProperty)[idProperty]; // Increment integer id or generate string id
return _.isFinite(id) ? ++id : nanoid(7);
}
}

API request succeds but catch is executed instead of then?

I have this weird error in my React app at the moment. I am sending an api request and I want to do something if it succeeds and something else if I get an error back. The api requests succeeds, the post is getting approved, but the catch clause is executed instead of then.
Can you see something in this code that might make that happen?
The request which I am talking about is the Request.post one... the large one that ecompasses a few other requests.
export const approvePostSubmission = (post, date) => dispatch => {
const label = `${post.campaign_product_name} on ${moment(date).format('LL')}`;
if (post.post_type === 3) {
dispatch(sendGoogleEvent(GOOGLE_EVENT.STORY.APPROVE, label));
} else {
dispatch(sendGoogleEvent(GOOGLE_EVENT.POST.APPROVE, label));
}
dispatch({
type: APPROVE_POST_PENDING,
});
return Request.post(
API_ENDPOINT.POST_APPROVE(post.id),
{ publish_at: date },
false
)
.then(response => {
const { selectedContent } = store.getState().inbox;
dispatch(getUserWallet());
dispatch({
type: APPROVE_POST_SUCCESS,
});
const getPostTypeText = post_type => {
switch (post_type) {
case 3:
return 'Story';
case 4:
return 'IGTV Post';
case 5:
return 'Carousel';
case 6:
return 'IG Live';
default:
return 'Post';
}
};
const postType = getPostTypeText(selectedContent.post.post_type);
setTimeout(() => {
toast.show(
<p>
{`Woo! You approved a ${postType}! It will be published on `}
<RouterLink
to="/calendar"
color="#0dd36b"
onClick={e => toast.hide()}
>
{`${moment(date).format('LL')} 🙌`}
</RouterLink>
</p>,
{
type: 'success',
dismiss: true,
}
);
}, 100);
// Send slack bot message
Request.post(`${SLACKBOT.URL}/new-post`, {
post_status: 1,
post_type: selectedContent.post.post_type,
post_id: selectedContent.post.id,
campaign_name: selectedContent.post.campaign_product_name,
influencer_id: selectedContent.influencer.id,
influencer_name: selectedContent.influencer.full_name,
campaign_id: selectedContent.post.campaign_id,
post_image: selectedContent.post.image_url,
slack_channel: SLACKBOT.CHANNELS.NEW_POST,
})
.then(data => {})
.catch(err => console.error(err));
return response;
})
.catch(err => {
setTimeout(() => {
dispatch({
type: APPROVE_POST_FAIL_SHOW_ERR,
payload: !!err.response
? err.response.data.message
: 'Unable to approve post!',
});
!!err.response &&
toast.show(
`${err.response.data.message || err.response.data.error} 🚫`,
{ type: 'fail' }
);
setTimeout(() => {
dispatch({
type: APPROVE_POST_FAIL,
});
}, 3000);
}, 500);
});
};

React Native - Return value from event listener in a promise

This has more to do with promises and async/await than the package I am using but in any event, the package is react-native-background-upload and I have an issue with getting back the response from inside of the 'completed' event listener. I think my understanding of how these promises resolve might be wanting but I need to return the response from the server after the upload is complete. The example file provided here mostly caters for logging to the console, not returning data from the server.
async submit() {
const responsefromUpload = await this.videoUploader().then((data) => data);
console.log(responsefromUpload);
}
from which I call the function below
videoUploader() {
const { video } = this.state;
video.uri = Platform.OS == 'android' ? video.uri.replace('file://', '') : video.uri;
const options = {
url: 'https://upload.wistia.com',
path: video.uri,
method: 'POST',
field: 'file',
type: 'multipart',
};
return Upload.startUpload(options).then((uploadId) => {
console.log('Upload started');
Upload.addListener('progress', uploadId, (data) => {
console.log(`Progress: ${data.progress}%`);
});
Upload.addListener('error', uploadId, (data) => {
console.log(`Error: ${data.error}%`);
});
Upload.addListener('cancelled', uploadId, (data) => {
console.log('Cancelled!');
});
Upload.addListener('completed', (data) => {
// data includes responseCode: number and responseBody: Object
console.log('Completed!');
return data.resporesponseBody; // this return doesn't work
});
}).catch((err) => {
console.log('Upload error!', err);
});
}
Any assistance will be greatly appreciated.
wrap the code in .then((uploadId) => { ... } in a "new Promise" - resolve the promise in completed handler ... resolve(data.resporesponseBody);
i.e.
videoUploader() {
const {video} = this.state;
video.uri = Platform.OS == 'android' ? video.uri.replace('file://', '') : video.uri;
const options = {
url: 'https://upload.wistia.com',
path: video.uri,
method: 'POST',
field: 'file',
type: 'multipart',
};
return Upload.startUpload(options)
.then(uploadId => new Promise((resolve, reject) => {
console.log('Upload started');
Upload.addListener('progress', uploadId, data => {
console.log(`Progress: ${data.progress}%`);
});
Upload.addListener('error', uploadId, data => {
console.log(`Error: ${data.error}%`);
reject(data);
});
Upload.addListener('cancelled', uploadId, data => {
console.log('Cancelled!');
reject(data); //?
});
Upload.addListener('completed', data => {
// data includes responseCode: number and responseBody: Object
console.log('Completed!');
resolve(data.responseBody);
});
}))
.catch(err => {
console.log('Upload error!', err);
});
}
you can the wrap startUpload .then block code inside a Promise and resolve it on the completion of file upload.
function videoUploader() {
const { video } = this.state;
video.uri = Platform.OS == 'android' ? video.uri.replace('file://', '') : video.uri;
const options = {
url: 'https://upload.wistia.com',
path: video.uri,
method: 'POST',
field: 'file',
type: 'multipart'
};
return Upload.startUpload(options).then(uploadId => {
const uploadCompletionPromise = new Promise(function(resolve, reject) {
Upload.addListener('progress', uploadId, data => {
console.log(`Progress: ${data.progress}%`);
});
Upload.addListener('error', uploadId, data => {
console.log(`Error: ${data.error}%`);
});
Upload.addListener('cancelled', uploadId, data => {
console.log('Cancelled!');
});
Upload.addListener('completed', data => {
console.log('Completed!');
resolve(data.resporesponseBody);
});
});
return uploadCompletionPromise
.then(response => ({ success: true, data: response }))
.catch(error => ({ success: false, error }));
}).catch((error) => {
console.log('Upload error!', error);
return { success: false, error }
});
}

Categories