Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
onChange Not Updating State At Correct Time

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: https://codesandbox.io/s/amazing-river-o15h4?file=/src/Child.js

... And here is a screenshot of the console.log in the onChange and the setState call not updating: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>
  );
}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda