I want to rewrite following code from a Promise and ajax call to a fetch call in reactjs.
const self = {
fetchPreAuthnConfig: (data) => {
return new Promise((resolve, reject) => {
$.ajax({
url: preAuthnEndpoint,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data),
success: ({ configurations }) => {
resolve(configurations);
},
error: (error) => {
reject(error);
},
});
});
},
};
export default self;
So how I thought fetch would work was by replacing the ajax call to fetch. Something like this:
const self = {
fetchPreAuthnConfig: (data) => {
return new Promise((resolve, reject) => {
fetch(preAuthnEndpoint, {
method: 'post',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data),
}).then(configurations => {
return configurations;
})
.catch(error => {
throw error;
});
});
},
};
But that was not the case. I did go through the fetch api syntax but it was not clear enough on how to preserve the const self
part. Quite new to react programming hence I don't really know the workaround.