I am new to functional programming.
As I heard many times, functional programming could help with easier maintenance. So, I would like to see if it can help with this problem, or actually I may need to look for other solution. If other solution is needed, sorry for this misleading topic.
In my react project,
I have two states, one is Projection, other is called StressProjections
I have a function that will invoke two Api call, once the api return come back. It will update both state
Below is my code.
//call API1
const simulateionCall = new Promise((resolve, reject) => {
axios.post <
IProjectionResponse >
(`/api1`, normalProjectionRequest)
.then((data) => {
resolve(data);
})
.catch((err) => {
reject(err);
});
});
//call API12
const stressCall = new Promise((resolve, reject) => {
axios.post <
IStressProjectionResponse >
(`/api2`, stressProjectionRequest)
.then((data) => {
resolve(data);
})
.catch((err) => {
reject(err);
});
});
Promise.allSettled([simulateionCall, stressCall]).then((vals) => {
console.log(vals);
vals.forEach((val, index) => {
if (val.status === "rejected") {
if (index === 0) {
//ERROR handling api1
props.setProjection(resMock.results);
} else {
//ERROR handling api22
props.setStressProjections(res.results[0].scenarios);
}
} else {
if (index === 0) {
//Set content for api 1
// @ts-ignore
props.setProjection(val.value.data.result);
} else {
//Set content for api 2
// @ts-ignore
props.setStressProjections(val.value.data.results);
}
}
});
});
Question:
In my allsettle function, as you can see I need to check with the index before manually to assign which props.set function and which error handling should be call.
First 1, it is not readable, as some may wonder why we use this set function when it is in index 0.
Second2, it is hard in maintenance. When there are more and more Api call is included, my code would be full of conditional if (index === ...) , it increase the diffculty in reading
Hope I can see a new technique or functional way to cope with above two issues.