How can I print a switch's ON/OFF state?

Viewed 64

As given in this example: https://reactnative.dev/docs/switch.html I am trying to print the ON/OFF state of Switch in something like:

import React, { useState } from "react";
import { View, Switch, StyleSheet, Text } from "react-native";

const App = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  return (
    <View style={styles.container}>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
      <Text> Switch state is: {isEnabled} </Text>
    </View>
  );
}

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

export default App;

But, it doesn't print {isEnabled} value.

2 Answers

Your mistake is here. setIsEnabled(previousState => !previousState);

It should be setIsEnabled(!previousState)

The methods used for setting states just take a value as an argument, not a function.

Related