Search code examples
javascriptreactjsreduxreact-reduxreact-hooks

React useState is not picking initial state?


I need a form values to be pre-filled with initial values coming in from redux state:

Issue is, REDUX is updated, but useState is not using the initial values passed in.

// redux
const {
    [1]: stepInfo,
    error,
    saving,
} = useSelector((state) => state.implOnboard);

// local state
// setting up initial state
// =================================================================
const [name, setName] = React.useState(stepInfo.name);
const [description, setDescription] = React.useState(stepInfo.desc);
// =================================================================

Input elements (the other one has value={description})

both show empty fields instead of prefilled values

<input
  id="impl-name"
  placeholder="gs-sentiment-analysis-impl-1"
  value={name} // 👈 using here
  onChange={(e) => {
    setName(e.target.value);
    // enable the editing status to true for this step if any state changes
    setEditingStepStatus(1, true);
  }}
/>

Debug

  console.log(name, description); // prints '', ''
  console.log(stepInfo); // but this prints the actual values that I want to show

Solution

  • Okay, thanks to Drew Reese, I was able to understand the issue at hand.

    So I worked around and came up with this solution:

    // local state
    // setting up initial state
    // =================================================================
    const [name, setName] = React.useState(stepInfo.name);
    const [description, setDescription] = React.useState(stepInfo.desc);
    
    // workaround 👇
    React.useEffect(() => {
        setName(stepInfo.name);
        setDescription(stepInfo.desc);
    }, [stepInfo.name, stepInfo.desc]);
    // =================================================================