Home > Back-end >  useCallback not changing variable value
useCallback not changing variable value

Time:09-08

I am using ReactJS along side Foxglove Studio to create a custom panel with a slider on it. I have created the slider, but when I attach a callback to the onChange element of the slider the slider remains static and doesn't allow me to move it Static slider

let LEDValue: number | number[] = 0;

const sliderOnChange = useCallback(
  (_event: Event, value: number | number[]) => {
    if (value !== LEDValue) {
      value = LEDValue;
    }
  },
  [LEDValue],
);

const min = 0;
const max = 254;
const step = 1;
const marks = [
  { value: min, label: String(min) },
  { value: max, label: String(max) },
];

return (
  <div style={{ padding: "1rem" }}>
    <h2>{LEDValue}</h2>
    <Slider
      min={min}
      max={max}
      step={step}
      marks={marks}
      value={typeof LEDValue === "number" ? LEDValue : 0}
      onChange={sliderOnChange}
    />
  </div>
);

No errors when I build it, I just can't drag the slider and values don't update. Am I missing something?

CodePudding user response:

You can use useState to store Led value also the logic on function sliderOnChange doesn't seem correct

const [ LEDValue, setLEDValue ] = useState(Number);

const sliderOnChange = useCallback(
   (_event: Event, value: number | number[]) => {
      // If using useState
      setLedValue(Number(value));
   },
   [LEDValue],
);
  • Related