Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slider onChange callback can't see states of calling component #3250

Closed
ginfonic opened this issue Dec 28, 2022 · 4 comments
Closed

Slider onChange callback can't see states of calling component #3250

ginfonic opened this issue Dec 28, 2022 · 4 comments

Comments

@ginfonic
Copy link

What package has an issue

@mantine/core

Describe the bug

In Slider component when you use a custom callback in onChange prop that not only set a value but also uses internal states of calling component these states are invisible, undefined or 0.
The other Mantine components, Select for instance or the standard ones (input) can see calling component states in callback normally as it should be.
I hope it's a bug not a feature.

Снимок экрана 2022-12-28 в 11 36 12

log

What version of @mantine/hooks page do you have in package.json?

5.9.5

If possible, please include a link to a codesandbox with the reproduced problem

No response

Do you know how to fix the issue

No

Are you willing to participate in fixing this issue and create a pull request with the fix

None

Possible fix

No response

@rtivital
Copy link
Member

Slider onChange function is momoized to improve performance, it cannot reference state variables.

@frustak
Copy link

frustak commented Jan 10, 2023

I've found a workaround, you can use this component instead if memoization is making issues:

import { Slider, SliderProps } from '@mantine/core'
import { useDidUpdate } from '@mantine/hooks'

function SliderNoMemo(props: SliderProps) {
	const [value, setValue] = useState(props.value)

	useDidUpdate(() => {
		if (value) props.onChange?.(value)
	}, [value])

	useDidUpdate(() => {
		setValue(props.value)
	}, [props.value])

	return <Slider {...props} value={value} onChange={setValue} />
}

@rtivital
Copy link
Member

Duplicate of #2840

@rtivital rtivital marked this as a duplicate of #2840 Jan 17, 2023
@tscans
Copy link

tscans commented Jan 28, 2023

import { Slider, SliderProps } from '@mantine/core'
import { useDidUpdate } from '@mantine/hooks'

function SliderNoMemo(props: SliderProps) {
	const [value, setValue] = useState(props.value)

	useDidUpdate(() => {
		if (value) props.onChange?.(value)
	}, [value])

	useDidUpdate(() => {
		setValue(props.value)
	}, [props.value])

	return <Slider {...props} value={value} onChange={setValue} />
}

Not ideal but this worked and helped me. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants