0

I have the following code...

const Thing = ({...})=> {
    const initialState = {
        foo: ''
    }
    const [state, setState] = useState(initialState);
    const changeFormvalue = (e) => {
        state.foo = e.target.value;
        setState(state);
    }
    return (
        <input type="text" name ="foo"
               value={state.foo}
               onChange={changeFormvalue} />
    )
}

When I run I see it hit the function, and I see it set the value. However, after the setState command, the page does not rerender and the value is not updated.

Why is the page not updating?

JGleason
  • 3,067
  • 6
  • 20
  • 54

1 Answers1

0

Set the state properly (without mutating it).

See Refactored code below and read further on links provided in the question's comments.

const Thing = ({...})=> {
    const initialState = {
        foo: ''
    }
    const [state, setState] = useState(initialState);
    const changeFormvalue = (e) => {
        const value = e.target.value;
        setState(prev => ({...prev, foo: value, assetName: value}));
    }
    return (
        <input type="text" name ="foo"
               value={state.foo}
               onChange={changeFormvalue} />
    )
}
gdh
  • 13,114
  • 2
  • 16
  • 28
  • I would think if we are going to mark as duplicate the original post should be edited to make the question clearer – JGleason Jun 22 '20 at 15:00