score:1

Accepted answer

the generaterandomstock function creates a closure with initial data value. that's always an empty object {}. you can access the data received to the callback function to `setdata method where it gives updated values.

try like below

  const generaterandomstock = () => {
    const randnumber = math.floor(math.random() * 9 + 1).tostring();
    setdata((prevdata) => {
      console.log(prevdata);
      if (prevdata.hasownproperty(randnumber)) {
        return {
          ...prevdata,
          [randnumber]: prevdata[randnumber] + 1
        };
      } else {
        console.log("does not have");

        return {
          ...prevdata,
          [randnumber]: 1
        };
      }
    });
  };

edit wizardly-brattain-ycquuj

score:0

you need to add generaterandomstock function as a dependency in useeffect hook. since this function uses the data value, its content is updated when the data value is updated.

const [data, setdata] = usestate({});

  //generates a random number and updates the state
  const generaterandomstock = () => {
    const randnumber = math.floor(math.random() * 9 + 1).tostring();
    console.log(data);
    if (data.hasownproperty(randnumber)) {
      console.log("has");
      setdata((prevstate) => ({
        ...prevstate,
        [randnumber]: prevstate[randnumber] + 1
      }));
    } else {
      console.log("does not have");
      setdata((prevstate) => ({
        ...prevstate,
        [randnumber]: 1
      }));
    }
  };

  useeffect(() => {
    //interval to generate random number every 2 seconds
    const interval = setinterval(() => {
      generaterandomstock();
    }, 2000);

    return () => {
      clearinterval(interval);
    };
  }, [generaterandomstock]);

Related Query

More Query from same tag