i need to call an api depending on the value that im receiving on state,
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
const [selectedValue, setSelectedValue] = useState([])
const firstAPI = async (val) => {
return await axios
.get(`http://localhost:3000/api/v1/rendition?name=${val}&&excel=true`)
.then(res => console.log('excel', res))
}
const secondAPI = async (val) => {
const limit = pageSize * (page - 1);
return await axios
.get(`http://localhost:3000/api/v1/rendition?id=${val}&&skip=${limit}&&take=${pageSize}&&excel=true`)
.then((res) => {
console.log('excelID', res);
})
}
const handleExcelClick = (param) => {
if(param.filter(item => typeof item === 'string')){
firstAPI(param)
} else {
secondAPI(param)
}
}
<Button onClick={() => handleExcelClick(selectedValue)} > Excel </Button>
so im receveing a value from 2 different inputs, which are stored in selectedValue state, which can either be a string or a number, so i need to call an api depending on the value, if its a string, call the firstAPI, if it's a number, call the secondAPI. But whatever condition i put in, it ignores the if statement and just calls the first api which also triggers a 500 error because one of the apis only takes numbers as params, i don't know other way to approach this, any help will be much appreciated
CodePudding user response:
Try with:
...
if(param.filter(item => isNaN(item) )){
firstAPI(param)
} else {
secondAPI(param)
}
...
CodePudding user response:
So i solved it a lot of days ago, but i forgot to post my solution, so here it goes:
const handleExcelClick = (param: any) => {
if (typeof param === 'number') {
return firstAPI(param);
} else if (param.some((i: any) => typeof i === 'string')) {
return secondAPI(param);
}
};
i basically forgot to add a return to each statement, and there was also no point in filtering values based on just a filter method, so i used the "some" array method to just receive the values that return true if the condition is met, which is checking if the data type matches the statement
hope this helps anyone trying to do the same