I
I
Ivan Ivanovich2021-01-22 12:58:50
React
Ivan Ivanovich, 2021-01-22 12:58:50

Async in react?

Good day.

I am writing a simple todo in react + rudux.

The crux of the problem:

We have a todoDelete function that takes an id, then runs through the array of todos and deletes the desired element.

Next, we dispatch our action addTodos, which takes the current array of todos and updates it in the redux state.

After that, we must store our new todo array in localstorage, which is done by the addTodosToLocalStorage function .

todoDelete = (id) => {
    const { todos } = this.props;

    const newTodoList = todos.filter(item => item.id !== id);
    
    this.props.addTodos(newTodoList);
    setTimeout(() => this.addTodosToLocalStorage(), 0);
  }


The problem is that when we despatch the action addTodos
this.props.addTodos(newTodoList);
we need to wait for its execution, but this does not happen and the addTodosToLocalStorage function is executed earlier, which of course breaks the logic.

I found a crutch in the form of setTimeout 0, but is this a good solution to the problem? I don't think so.

Therefore, I want to ask you, how can you wait until dispatch addTodos has completed, and only after that call addTodosToLocalStorage?

With setState, you could simply pass callback as another argument, but I don’t know what to do in this case.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WbICHA, 2021-01-22
@WblCHA

await?
.then?

D
Denioo, 2021-01-22
@Denioo

todoDelete = async (id) => {
        const { todos } = this.props;

        const newTodoList = todos.filter(item => item.id !== id);

        await this.props.addTodos(newTodoList);
      }

And no timeouts are needed. https://learn.javascript.ru/async-await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question