0

I want the alert to display lineaData.name="new Name" and lineaData.age=33 when the button is clicked, but it keeps displaying the initial values. What wrong?

I'am using React 16.13.1

Thanks in advance.

  const TestComp = () => {
  const [lineaData, setLineaData] = useState({
    name: "",
    age: 0,
  });

  const [sendData, setSendData] = useState(null);

  const handleClick = () => {
    setSendData(true);
    alert(lineaData.name + " - " + lineaData.age);
  };

  useEffect(() => {
    if (sendData) {
      setLineaData({
        ...lineaData,
        name: "new Name",
        age: 33,
      });
    }
  }, [sendData]);

  return (
    <Grid>
      <FormControl style={{ width: "335px" }}>
        <FormControl>
          <TextField
            variant="outlined"
            type="text"
            label="Name:"
            name="name"
            onChange={(e) =>
              setLineaData({
                ...lineaData,
                name: e.target.value,
              })
            }
            value={lineaData.name || ""}
          />
          <FormHelperText>{lineaData.nameError}</FormHelperText>
        </FormControl>
      </FormControl>

      <Button type="submit" onClick={handleClick}>
        <img src="./imagenes/ok.png" align="right|middle" height="30" alt="" />
      </Button>
    </Grid>
  );
};
  • React states are async, it's unlikely `sendData` has been updated at the point you are calling the alert, let alone it having triggered and completed the update on `lineaData` – DBS Dec 02 '20 at 14:31
  • Does it not show the correct values in the form? It should be obvious that the useEffect hook hasn't run yet when you alert the values. – Guy Incognito Dec 02 '20 at 14:32
  • Any idea on how to structure the code? – user14749549 Dec 02 '20 at 15:15

2 Answers2

0

No need to use useEffect to get it to update. Just call setState directly in your handleClick function

  const handleClick = () => {
      setLineaData({
        ...lineaData,
        name: "new Name",
        age: 33,
      });
  };
Jonathan Irwin
  • 5,009
  • 2
  • 29
  • 48
  • This code doesn't works. The first time the button is clicked, alert shows the variables in blank. The second time it brings the values I expect. – user14749549 Dec 02 '20 at 17:00
0

I'm not totally sure what you want to accomplish but I think you can get rid of the sendData-state and the UseEffect-hook.

Just set the state of lineaData in handleClick like so:

const handleClick = () => {
    setLineaData({
        name: "new Name",
        age: 33,
    });
    alert("new Name - 33");
};

Besides you don't need to spread lineaData when you set all props.

dyedwiper
  • 151
  • 12
  • The idea is to update an object before sending it to a Node back end. When the object is update with data coming from a component event, like the textField's onChange, everything is ok. But setting the state in handleClick is not working. – user14749549 Dec 02 '20 at 17:07
  • As mentioned in a comment above, you cannot tell if the state update worked by the alert right after, because state updates are asynchronous. (I edited my answer in respect of that.) I see no reason why the state update should not work in the handleClick. – dyedwiper Dec 03 '20 at 09:13
  • Does the value of your TextField update after you click the button? – dyedwiper Dec 03 '20 at 09:19
  • Yes, Textfield's value is updated. That's clear to me now. Thanks a lot. – user14749549 Dec 03 '20 at 11:10