I have the following functions in react const reload = async(index) => {…
- User
I have the following functions in react const reload = async(index) => { setNomenclaturaFull([]); setSelectOption([]); getHouses(nomenclaturas); setSelectOption(nomenclaturaFull[index]); console.log("reloaded"); };
const getHouses = (nomenclaturas) => { let houses = nomenclaturas.data.map(async (item, index) => { let data = { ...item }; let houses = await getNomenclaturasCasasHelper( "Yd5MV7jkA0MjQeCmzKrZ", nomenclaturas.data[index].id ).then((houseData) => { data.houseData = houseData; }); return data; }); Promise.all(houses).then((data) => { setNomenclaturaFull(data); }); };setSelectedOption is setting up the older version of the variable nomenclaturas, I want it to wait for getHouses to set the new version of nomenclaturas
- Assistant
You can achieve this by modifying the
reloadfunction to useawaitwhen calling thegetHousesfunction, and then callsetSelectedOptionaftergetHousesare updated. To do this, you need to return a promise from thegetHousesfunction:const reload = async (index) => { setNomenclaturaFull([]); setSelectOption([]); await getHouses(nomenclaturas); setSelectOption(nomenclaturaFull[index]); console.log("reloaded"); }; const getHouses = (nomenclaturas) => { return new Promise(async (resolve) => { let houses = nomenclaturas.data.map(async (item, index) => { let data = { ...item }; let houses = await getNomenclaturasCasasHelper( "Yd5MV7jkA0MjQeCmzKrZ", nomenclaturas.data[index].id ).then((houseData) => { data.houseData = houseData; }); return data; }); Promise.all(houses).then((data) => { setNomenclaturaFull(data); resolve(); }); }); };This way,
setSelectOptionwill wait forgetHousesto finish updating thenomenclaturaFullbefore setting the new selected option.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.