I am new to React, and I am having the following issue:
When I get a value from redux
, I am creating a clone of it and saving it to useState
so I can modify it without affecting the original value until I press save, which then sends the value to redux to be updated in my store. The problem I am having, is in the function saveProject
the value doesn’t change name
within the object, as it is still the original value. However, in the effect
, the correct value is displayed. I am not sure why, what would be causing this?
// Edit dialog
export default () => {
// Original value from redux
const active = useSelector(selectActiveProject);
// The value I want to track
const [project, setProject] = useState<Project>(Object.assign({}, active));
// The value should be the updated value here (but shows the original)
const saveProject = () => console.log(project);
// Sets the value when the input is typed into
const nameChange = (e: BaseSyntheticEvent) => setProject({ ...project, name: e.target.value });
// Prints the correct value from the input
useEffect(() => console.log('useEffect', project), [project]);
return (
<>
<input defaultValue={project.name} onChange={e => nameChange(e)} />
<button onClick={saveProject}>Save</button>
</>
);
}