1
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useState } from "react";

export default function App() {
  const [item, setItems] = useState([]);
  const [button2, setbutton2] = useState(
    <TouchableOpacity onPress={() => makenewButton()}>
      <Text>Click2</Text>
    </TouchableOpacity>
  );

  const addItem = () => {
    setItems([...item, { key: 0, value: 1 }]);
  };
  const makenewButton = () => {
    setbutton2(
      <TouchableOpacity onPress={() => setNode()}>
        <Text>Click3</Text>
      </TouchableOpacity>
    );
  };
  const setNode = () => {
    addItem();
  };
  return (
    <View style={styles.container}>
      {item.map((item) => (
        <Text>{item.value}</Text>
      ))}
      <TouchableOpacity onPress={() => addItem()}>
        <Text>Click1</Text>
      </TouchableOpacity>
      {button2}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

This is my entire code.

  1. I made two methods to execute additem.
  2. One is to run onpress when click1 is pressed.
  3. when I press click 1, addItem works as I thought.
  4. However, the click3 button made through click2 is not the same.
  5. It does not add elements to the array, it simply changes the value.
  6. I want to add elements to the arrangement in click3 which is made through click2.

I am using React Native and Expo and need help with this problem.

Thank you for your time and if you know the answer to the above question, please give me some advice.

  • Does this answer your question? [Push method in React Hooks (useState)?](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) – Naren Jan 13 '21 at 17:57

1 Answers1

0

Change your addItem function and pass setItems the previous value of the state:

const addItem = () => {
  setItems(prev=>[...prev, { key: 0, value: 1 }])
};
WebbH
  • 2,379
  • 1
  • 15
  • 26