A
A
Andrey Ivanov2020-09-17 11:06:24
JavaScript
Andrey Ivanov, 2020-09-17 11:06:24

Why is the text input field being cleared?

Hey! I moved a large piece of code to the sandbox, in the hope that you will help).
This is a block with 2 text fields and 1 field for attaching a picture. I caught a bug, - the script
1) print something in the first text field
2) attach a file
3) see that the text field (in step 1 that was entered) was cleared.
The question is why was it cleared?
I tried to debug, I saw that onChange in EditorBlockItem is executed twice, if you follow the script, I set the console.log - no results..

Sandbox

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twolegs, 2020-09-17
@newdecline

const onDrop = useCallback(async (acceptedFiles) => {
    const newImage = acceptedFiles[0];
    let hasError;

    if (newImage.size > allowedMaximumFileSize) {
      hasError = true;

      alert("Размер файла не допустим");
    }

    if (!allowedMimeTypes.includes(newImage.type)) {
      hasError = true;

      alert("Тип файла не допустим");
    }

    if (!hasError) {
      const previewBASE64 = await fileReader(newImage);

      onImageChange(name, { file: newImage, preview: previewBASE64 });
    }
  }, []);

Here you have no onImageChange in the dependency array. Accordingly, onImageChange is always executed with the initial value (that is, empty fields).
PS If you add onImageChange dependencies, then memoization will be useless, because above you create this function every render.

P
Pavel Didenko, 2020-09-17
@Dasslier

const onChange = (name, value) => {
    setFormFields((prevState) => ({
      ...prevState,
      [name]: value
    }));
  };

This is where you replace the entire state object, so it clears

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question