Home > Software design >  onChange Not Updating State At Correct Time
onChange Not Updating State At Correct Time

Time:02-14

I'm trying to save the value of the input field to state. When the defaultValue is 'projectName', and I delete the word 'Name' from the input field, I want the state to update so that the defaultValue is 'project'. When I console.log e.target.value in the onChange, I can see the change happening when I make the deletion, and my code in the onChange is saving the value to state, but unfortunately, the state does not update. Any thoughts as to why?

Here is a Code Sandbox: enter image description here

App.js

import "./styles.css";

import Child from "./Child";

export default function App() {
  const thisIsState = {
    id: 1,
    projectName: "projectName",
    description: "description"
  };

  return (
    <div className="App">
      <Child project={thisIsState} />
    </div>
  );
}

Child.js

import { useState, useEffect } from "react";
import "./styles.css";

export default function Child(props) {
  console.log(props);
  const [state, setState] = useState({
    projectName: "",
    description: ""
  });

  let project = props.project;
  let errors = props.errors;
  useEffect(
    (state) => {
      setState({
        ...state,
        projectName: project.projectName,
        description: project.description
      });
      console.log("useEffect1 state: ", state);
    },
    [project, errors]
  );

  const onChange = (e) => {
    console.log("e.target.value in onChange: ", e.target.value);
    setState((state) => ({
      ...state,
      [e.target.name]: e.target.value
    }));
    console.log("onChange() state: ", state);
  };
  return (
    <div className="App">
      <form>
        <input
          type="text"
          placeholder="Project Name"
          name="projectName"
          defaultValue={props.project.projectName}
          onChange={onChange}
          style={{ marginBottom: "15px" }}
        />
        <br />
        <input
          type="text"
          placeholder="Project Name"
          name="projectDescription"
          defaultValue={props.project.description}
          onChange={onChange}
        />
      </form>
    </div>
  );
}

CodePudding user response:

Try something like this in your Child component instead of console.log(props). Props does not change because you did not change default state. If you try to log actual state, it is changing.

const [state, setState] = useState({
    projectName: "",
    description: ""
  });
console.log(state);

CodePudding user response:

This question has already been answered in a different question. The thing is setstate function is asynchronous. To overcome this you can use callback functions to print the state after it is updated. The link to the original answer is below State not updating when printing on same function where updating in React Js

  • Related