Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

I have the following functions in react const reload = async(index) => {…

  1. 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

  2. Assistant

    You can achieve this by making use of useEffect hook, which allows you to perform side effects in function components. Here's how you can modify your code:

    1. Add useState for a new loading state:
    const [loading, setLoading] = useState(true);
    
    1. Set loading to true at the beginning of the reload function:
    const reload = async (index) => {
      setLoading(true);
      setNomenclaturaFull([]);
      setSelectOption([]);
      getHouses(nomenclaturas);
    };
    
    1. Set loading to false after setting nomenclaturaFull in getHouses:
    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);
      });
    };
    
    1. Use useEffect to update the selectOption when loading state changes:
    useEffect(() => {
      if (!loading) {
        setSelectOption(nomenclaturaFull[index]);
        console.log('reloaded');
      }
    }, [loading]);
    

    Now, the setSelectOption will only be called after the new version of nomenclaturas is set, thus avoiding any problems caused by the state update delay. Make sure to import useEffect from 'react' for this to work.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.