Home > other >  TypeScript - React Native : what is the way to switch between cases in the example?
TypeScript - React Native : what is the way to switch between cases in the example?

Time:08-03

 const [darkMode, setDarkMode] = useState(false);
  const toggleDarkMode = () => setDarkMode(previousState => !previousState);

  const [locationName, setLocationName] = useState(false);
  const toggleLocationName = () => setLocationName(previousState => !previousState);

  const [diameter, setDiameter] = useState(false);
  const toggleDiameter = () => setDiameter(previousState => !previousState);

how can i do a switch case with just one function in my example ?

as you can see that the "toggleFunc" appears with different names.

"const toggleFunc = () => setDarkMode(previousState => !previousState);"
const filterFunctions = (toggleFunc: () => void, setOfVal: any) => {
switch (setOfVal) {
case darkMode: 
 return () => setDarkMode(previousState => !previousState);
 case locationName:
        return () => setLocationName(previousState => !previousState);
 case diameter:
        return () => setDiameter(previousState => !previousState);
    }
  };

CodePudding user response:

I Would do it this way it's much more cleaner in my opinion

 const [darkMode, setDarkMode] = useState(false);
 const [locationName, setLocationName] = useState(false);
 const [diameter, setDiameter] = useState(false);


 const toggles = {
    diameter: () => setDiameter(p => !p),
    darkMode: () => setDarkMode(p => !p),
    locationName: () => setLocationName(p => !p),
 }

then you call each function like this

toggles.darkMode()

  • Related