I
I
Ismail2020-05-14 14:15:32
JavaScript
Ismail, 2020-05-14 14:15:32

Why is the value in input not changing?

Good time of the day. You need to change the value in input, and in onChange make a patch request to the server. But there is a problem, when the value changes, the value in the input itself does not change in any way, while a request is sent to the server, but only + - 1 letter. What is the problem?

input component

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: "25ch",
      display: "flex",
      textAlign: "center",
      justifyContent: "center",
      justifyItems: "center",
      justifySelf: "center",
    },
  },
}));

const ItemStatusTitle = ({ todo_id, item_id, title, patchItem }) => {
  const useStyleClasses = useStyles();

  const [value, setValue] = React.useState(title);

  React.useEffect(() => {
    setValue(title);
  });

  const changeTitle = (event) => {
    setValue(event.target.value);
    patchItem(todo_id, item_id, "title", event.target.value);
  };

  return (
    <form className={useStyleClasses.root} noValidate autoComplete="off">
      <TextField
        id="title"
        variant="outlined"
        value={value}
        onChange={changeTitle}
      />
    </form>
  );
};

export default ItemStatusTitle;



patchItem

axios
        .patch(`http://localhost:8080/api/v1/items/${item_id}`, {
          item: {
            title: title,
          },
        })
        .then((response) => {
          let ids = [];

          this.state.items.map((item) => {
            ids.push(item.id);
            return null;
          });

          const itemIndex = ids.indexOf(response.data.id);
          const items = update(this.state.items, {
            $splice: ,
          });

          this.setState({ items: items });
        });



This is how it looks

Заметно, что тайтл в правом box не изменился, а в маленькой карточке добавилась лишь одна буква
5ebd282393053592009726.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2020-05-14
@gosugod

This code is run on every render

React.useEffect(() => {
    setValue(title);
});

Perhaps you wanted to write
React.useEffect(() => {
    setValue(title);
}, []); // < пустой массив, чтобы эффект выполнился ровно один раз

I
Ismail, 2020-05-14
@gosugod

Solved the problem. You need to pass [title] to useEffect:

React.useEffect(() => {
    setValue(title);
  }, [title]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question