D
D
Danil Zinchenko2020-06-08 17:25:53
React
Danil Zinchenko, 2020-06-08 17:25:53

Why do you have to use async in React to get what you want?

Maybe the method is crooked, but it works.
I know that this.state works in react asynchronously, as far as I understand. But here I am using Mobx and I don't have this.state anywhere.

const textInput = useRef(null);

const editTodo = async () => {
 await onEditTodo(id);
 console.log("textInput.current", textInput.current);
};

// код

return (
  <input ref={textInput} />
);


Here. in this example, I use Ref in the component itself (my component is functional).
And when I click on the button, the editTodo function is called .
In the console now it displays the input I need, I hung the ref on it.
I use the console for clarity, so that errors do not immediately pop up if something happens.

But here, without async await , this does not work, output null to the console.
I understand that I am doing something wrong.

In general, my task is this: in the application, when editing a specific todo , put focus on this input. I would take it by className, but right there I need to put the focus in the Todo that I clicked on.

Here is a screenshot of my application:
5ede49b838591349139826.png

Perhaps there is a better way to set focus to the desired input when the button is clicked?

I use: Mobx (store is in a separate file).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-06-08
@danilzin

because everything is re-rendered, and the focus is lost
, you can solve it with a similar hack, but in general I’ll listen if there are other options

setTimeout(() => {
   textInput.current.focus()
}, 0)   // сработает в следующем цикле event loop-a после рендера

I would take it by className, but right there I need to put the focus in the Todo that I clicked on

you can add an ID-type attribute to the data input, and choose the one you need somehow in the spiritdocument.querySelector('input[data-id="456"]')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question