Is there an issue with my useState? I feel the values are not truing up right in my Array ReactNative

Viewed 44

Been so curious about my console.log output.

I have a button, when clicked it should basically add 1 to the use-State(1) I have created but it seems that I am doing something wrong; Please I need help with know if I am managing my State correctly {I am using React HOOKs}

const [procedureCounter, setProcedureCounter] = useState([1]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...ProcedureCounter,
  {
    id: procedureCounter.length,
    //value: procedureCounter + 1 // value is undefined for some reason so I removed it but still works
  },
]);
console.log(ProcedureCounter);


{       procedureCounter.map((item, value) => (
        <View style={{ marginVertical: 15 }} key={item.id + 1}>
          <ProcedureSteps step={value + 1} /> //This is a TexteInput Form 
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
    </TouchableOpacity>

Once 'ADD Button' is pressed it does not start from 2 as I have 1 set as initialState. Below is my Terminal Output after clicking or Pressing 'Add Button' 3 Times

This is what I get in-state Array I think it is wrong after clicking the button 3 times

The first step is set to 1 but 2,3,4 is when the button is clicked

Thank you for taking the time to look into this. I really hoped I explained this as best as I can. Thank you again!

1 Answers

First, have a consistent data type in your state so that is will easy mapping over values to create components.

const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);

The reason you are getting undefined is you are not accessing the array properly. Check the below snippet to see how to use it. I have also updated the map iteration for component creation.


const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...procedureCounter,
  {
    id: procedureCounter[procedureCounter.length -1].id + 1,
    value: procedureCounter[procedureCounter.length -1].value + 1
  },
]);
console.log(procedureCounter);

{       procedureCounter.map((item) => (
        <View style={{ marginVertical: 15 }} key={item.id}>
          <ProcedureSteps step={item.value} /> //This is a TexteInput Form 
        </View>
      ))}

<TouchableOpacity onPress={addProcedureHandler}>
      ADD Button
</TouchableOpacity>
Related