Topic: Using MDBTimepicker to setState sends my app into an update loop.
launchbrigade pro premium priority asked 3 years ago
Expected behavior
I can use onChange to store the users choice.
export default function Component() {
function handleTimepicker(e) { setNewBlock({ ...newBlock, armtime: e }) }
return (
<MDBTimepicker format='24h' onChange={handleTimepicker}/>
)
}
Actual behavior
Maximum update depth exceeded.
I have other input components like MDBInput and MDBCheckbox that both use the same logic (onChange pointing to a function with a setState) and dont cause this. Anyone know what my issue is?
Krzysztof Wilk staff answered 3 years ago
Hi!
It looks like the onChange method is causing that bug when you are trying to set the state which is an object. It works perfectly then the state contains only string value, so I'm afraid you have to store it separately until we fix this bug. Or you can edit the source code of this component - you should have an access to the repository of the MDB5 React Pro Essential/Advanced package where you can find that :)
Keep coding!
clickstudioltd pro premium priority answered 3 years ago
Actually couple of components have this behavior not just the time picker. The cause of this issue is that when you set the state in the parent component, it causes a rerender so that all the child components should be rendered again and on the second render onChange
is called again so it does the same thing over and over which causes the infinite loop.
I solved this by checking the value I have set before, if the new value is same as the old one, i skip setState
otherwise I set the new value:
<MDBTimepicker onChange={(time) => data.time !== time ? setData('time', time) : null} />
s.jakubowski staff commented 3 years ago
Soon we will be taking a closer look at this bug but at the moment you can use your solution.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Pro
- Premium support: Yes
- Technology: MDB React
- MDB Version: MDB5 3.0.0
- Device: Macbook Pro
- Browser: Chrome 100.0.4896.127
- OS: OS X Monterey
- Provided sample code: No
- Provided link: No