Search code examples
reactjsreact-nativeviewtouchableopacity

Why do I need to click twice on the TouchableOpacity?


I want to create a button where if you click on it you copy the color of the said button. But I need to click twice in order to copy my color (the first time I copy nothing) Can someone help me or tell me where I made the error? Here is my code :

  const [couleur, setCouleur] = useState("");
  async function cop() {
    await navigator.clipboard.writeText(couleur);
    alert("Couleur copiée");
  }

           <TouchableOpacity
                onPress={() => {
                  setCouleur("black");
                  cop();
                }}
              >
                <View
                  style={{
                    width: "100%",
                    height: 30,
                    backgroundColor: "#ADDAD4",
                  }}
                >
                  <Text style={styles.textcol}>green-8</Text>
                </View>
              </TouchableOpacity>
 textcol: {
    fontSize: 12,
    marginLeft: "75%",
    fontWeight: "300",
    textAlign: "center",
    alignItems: "center",
    alignSelf: "center",
    marginTop: "2%",
    color: "white",
    fontStyle: "italic",
  },

Solution

  • You need to do 2 things:

              <TouchableOpacity
                onPress={() => {
                  setCouleur("#black");
                }}
              >
    

    as well as add an UseEffect at the beggining:

      useEffect(() => {
    if (couleur !== "") {
      cop();
    } },[couleur]);