Sharcoux / slider

React-Native and React-Native-Web compatible slider
ISC License
161 stars 31 forks source link

Incorrect value being set #86

Closed findhumane closed 1 year ago

findhumane commented 1 year ago

Describe the bug

My use case is that the first time a user changes the slider, I want to show a popup and reset the slider's value back to what it was before. So I use React.useRef to save/update the current value of the slider any time it changes, and then when the value of the slider is updated, I check if the value has changed and try to set it back to the previously recorded value, but what I see is that Slider is using the incorrect value:

import * as React from 'react';
import { Button, View } from 'react-native';
import { Slider } from '@react-native-assets/slider';

export default function App() {
  const [selectedValue, setSelectedValue] = React.useState(1);
  const previousValue = React.useRef(1);

  React.useEffect(() => {
    if (selectedValue != previousValue.current) {
      alert('changed from ' + previousValue.current + " to " + selectedValue);
      setSelectedValue(previousValue.current);
    }
  }, [selectedValue]);

  return (
    <View style={{ padding: 20 }}>
      <Slider
        value={selectedValue}
        onValueChange={(newValue) => {
          alert("Setting newValue " + newValue);
          previousValue.current = selectedValue;
          setSelectedValue(newValue);
        }}
        minimumValue={1}
        maximumValue={3}
        step={1}
        style={{ width: 100 }}
      />
    </View>
  );
}

To Reproduce

Expected behavior

Slider should change the value to 1

Screenshots

N/A

Please complete the following information:

Additional context

I skipped the actual logic that handles the popup just the first time as this was enough to demonstrate the problem.

Sharcoux commented 1 year ago

You should be using onSlidingComplete instead of onValueChange. That will fix your issue.

findhumane commented 1 year ago

That worked, thanks!