I create a component which have to call 3 api.
The issue is with one of the call I have to do a filter on the 2 others one but if I do this I have an infinite loop because I set so the component is re-render
const component = ({}) => {
const [selectedDataFromTabA, setSelectedDataFromTabA] = React.useState(null)
const [selectedDataFromTabB, setSelectedDataFromTabB] = React.useState(null)
const { data, loading, error} = useFetch(getData())
const { data: dataTabA, loading: loadingTabA, error: errorTabA} = useFetch(getDataTabA())
const { data: dataTabB, loading: loadingTabB, error: errorTabB} = useFetch(getDataTabB())
if (loading|| loadingTabA|| loadingTabB)
return "loading"
if (error|| errorTabA|| errorTabB)
return 'eror'
setSelectedDataFromTabA(dataTabA.filter(x => x.IdTabA == data[0].IdTabA ))
setSelectedDataFromTabB(dataTabB.filter(x => x.IdTabB == data[0].IdTabB ))
return <div>NULL</div>
}
The problem is if I put my sets in useEffect it will call 2 or 3 times my api. So how can I avoid infinite loop and multi calls on api.
function useFetch(serviceFunctionApiCall) {
const [loading, setLoading] = React.useState(true)
const [error, setError] = React.useState(false)
const [data, setData] = React.useState(null)
React.useEffect(() => {
const init = async () => {
var response = await serviceFunctionApiCall
if (response.status != 200) {
setError(true)
} else {
setData(response.data)
}
setLoading(false)
}
init()
}, [])
return {
loading,
error,
data,
setData
}
}