Home > database >  React-Native Switch uncontrolled using an object doesn't change value
React-Native Switch uncontrolled using an object doesn't change value

Time:11-22

I have a react-native project in which I'm trying to handle the Switch component in a way that I can dynamically set an object with the boolean and its value, but I doesn't respond well:

Initially I use useEffect to process the data:

 useEffect(() => {
    let lista = {}
    Object.entries(planes).forEach(([j, plan]) => {
      lista[plan.nombre] = false
    })
    setSeleccion(lista)
  }, []);

Then I loop through my data to load it and create the "card" dynamically with a Switch:

<Switch
            offTrackColor="indigo.100"
            onTrackColor="indigo.300"
            onThumbColor="coolgray.500"
            offThumbColor="indigo.50"
            size="lg"
            onToggle={(val) => toggleSwitch(val, plan.nombre)}
            value={seleccion[plan.nombre]}
          />

Then toggle function:

 const toggleSwitch = (val, plan) => {
   setSeleccion({...seleccion, [plan]: val})
 };

Now if I print the new array it shows as expected:

useEffect(() => {
    console.log(seleccion)
  }, [seleccion]);

But sadly the Switch remains as false visually (just goes back to its false state, so one cant toggle back to off/false).

If I do a toString(seleccion[plan.nombre]) in the render it shows [object Undefined]

CodePudding user response:

Assuming that the Switch that you used is same/from react-native. There shouldn't be a prop called onToggle in Switch like you wrote below.

 <Switch
  offTrackColor="indigo.100"
  onTrackColor="indigo.300"
  onThumbColor="coolgray.500"
  offThumbColor="indigo.50"
  size="lg"
  onToggle={(val) => toggleSwitch(val, plan.nombre)}
  value={seleccion[plan.nombre]}
/>

instead, you need to use onValueChange

<Switch
  offTrackColor="indigo.100"
  onTrackColor="indigo.300"
  onThumbColor="coolgray.500"
  offThumbColor="indigo.50"
  size="lg"
  onValueChange={(val) => toggleSwitch(val, plan.nombre)}
  value={seleccion[plan.nombre]}
/>

You can read more about the props in Switch here

  • Related