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 making use of
useEffecthook, which allows you to perform side effects in function components. Here's how you can modify your code:- Add
useStatefor a new loading state:
const [loading, setLoading] = useState(true);- Set
loadingtotrueat the beginning of thereloadfunction:
const reload = async (index) => { setLoading(true); setNomenclaturaFull([]); setSelectOption([]); getHouses(nomenclaturas); };- Set
loadingtofalseafter settingnomenclaturaFullingetHouses:
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); setLoading(false); }); };- Use
useEffectto update theselectOptionwhenloadingstate changes:
useEffect(() => { if (!loading) { setSelectOption(nomenclaturaFull[index]); console.log('reloaded'); } }, [loading]);Now, the
setSelectOptionwill only be called after the new version ofnomenclaturasis set, thus avoiding any problems caused by the state update delay. Make sure to importuseEffectfrom 'react' for this to work. - Add
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.