Raphael
Raphael

Reputation: 107

correct update of state array in reactjs

i tried to build a TODO app with React Native

const [ enteredGoal, setEnteredGoal ] = useState("");
const [ courseGoals, setCourseGoals ] = useState([]);

const goalInputHandler = (enteredText) => {
  setEnteredGoal(enteredText);
};


const addGoalHandler = () => {
  let arrGoals = courseGoals;
  arrGoals.push(enteredGoal);
  setCourseGoals(arrGoals);
};

return (
    <View style={styles.screen}>
      <View style={styles.inputContainer}>
        <TextInput style={styles.input} onChangeText={goalInputHandler}/>
        <Button title="ADD" onPress={addGoalHandler}/>
      </View>
      <View>
        { 
          courseGoals.map((goal) => {
            <View key={goal} style={styles.listItem}><Text>{goal}</Text></View>
          })
        }
      </View>
    </View>
  );

the idea is to list the setCourseGoals array, but apparently after assigning a new text, it doesn't list anything. Its not until the text changes that the list is re-rendered. Any idea on why this happens?? the "useState" function is asynchronous, which assigns the value after rendering? Thanks in advance.

Upvotes: 0

Views: 45

Answers (1)

Isaac
Isaac

Reputation: 12874

The problem is coming from addGoalHandler

const addGoalHandler = () => {
  let arrGoals = courseGoals;
  arrGoals.push(enteredGoal);
  setCourseGoals(arrGoals);
};

What happened was you are using push method to push it to courseGoals which was mutated the state, one of the option you can do is update to below

const addGoalHandler = () => {
  let arrGoals = [...courseGoals, enteredGoal];
  setCourseGoals(arrGoals);
};

The idea is that, using spread syntax allowing you to create a new copy of array instead of mutated the previous state, and of course it can be shorten down to single line as below

const addGoalHandler = () => setCourseGoals([...courseGoals,enteredGoal])

Upvotes: 2

Related Questions