Home > other >  state update from a callback
state update from a callback

Time:12-18

The following member function populates folder_structure object with fake data:

    fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean>
    {
        return new Promise((resolve, reject) => {
            for (let i_ = 0; i_ < folders_; i_  ) {
                progress_callback_(i_ / folders_ * 100.);

                this.add(this.id(), faker.address.city()   i_, random_choice(this.folder_structure_id()));
            }

            progress_callback_(folders_ / folders_ * 100.);

            resolve(true);
        })
    }

It uses a callback to update the progress within the for loop which is then used to update the state (a progress bar) from within a useEffect() function with an empty array dependency array.

   let [progress_state_, set_progress_state_] = useState<number>(0);

    let [fake_done_, set_fake_done_] = useState<boolean>(false);

    useEffect(() =>
    {
        if (fake_)
            folder_structure_.fake(fake_, (progress_) => {
                set_progress_state_(progress_)
            }).then(value => set_fake_done_(value));
    }, [])

    if (!fake_ || fake_done_) etc etc```


However, the state is not updated (logging the progress in the console seems to work fine). Any ideas as to whether it's possible to update a state from within useEffect.? 

CodePudding user response:

The reason your useEffect hook isn't working is that it's not called upon progress_state_ state change.

Instead of

useEffect(() =>
    {
        ...
    }, [])

Try this instead

useEffect(() =>
    {
        ...
    }, [progress_])

Adding progress_ to the dependency array means useEffect will be called every single time progress_ changes. If you leave it as an empty dependency array, then useEffect is only ever called in the very beginning on when the code is mounted to the DOM.

Here's a good explanation on dependency arrays: https://devtrium.com/posts/dependency-arrays

CodePudding user response:

Addressing your final question: Yes, it is possible to update state from within useEffect.

To understand the root of your main issue, I would be curious to see how you are doing your logging. Are you logging from within fake() or from your render() function?

  • Related