проблема в асинхронном характере useState fns
Вы находитесь в console.log()
внутри того же самого useEffect () до того, как setState fn обновит значение.
useEffect(() => {
let others = [];
checkForAvailableAgent(
`sales_${i18n.language}`,
"LinkToStudio",
"ServiceID")
.then(res => { setDefaultStudioAvailable(res); })
.catch(error => { console.log("an error happened."); });
for (const studio of otherStudios) {
checkForAvailableAgent(
`sales_${studio}`,
"LinkToStudio",
"ServiceID"
)
.then(res => {
others[studio] = res; // here you are not using the updated value anywhere, so no problem here
setOtherStudiosAvailable(others); // the asynchronous setState has been called, the callback can be obtained with a useEffect on the updated state value
})
.catch(error => {console.log("an error happened."); });
}
console.log("others[studio]: ", others); //using a local variable, should log fine
console.log("other studios available: ", otherStudiosAvailable); // the otherStudiosAvailable has not been updated yet., uses the previous value []
}, [defaultStudioAvailable, i18n.language]);
}
Чтобы получить значениепосле его обновления используйте Effect on otherStudiosAvailable
useEffect(() => console.log(otherStudiosAvailable), [otherStudiosAvailable])
Обновление
Вместо нескольких условных операторов было бы лучше упростить структуру как
{defaultStudioAvailable && (
<Button
variant="success"
className="btn-xlarge"
onClick={e => callBtnClick("direct")}
>
{t("callBtn")}
</Button>
)}
{otherStudiosAvailable&& otherStudiosAvailable.length && ( //otherStudiosAvailable is an [] and always truthy
<Button
variant="success"
className="btn-xlarge"
onClick={e => callBtnClick("flag")}
>
Other studios available
</Button>)}
В вашем коде otherStudiosAvailable был в else
части троичного оператора, поэтому даже если он имеет значения, он не запустится, если defaultStudioAvailable верен