Topic: Infinite loop when setting state as object from MDBSelect getValue()
Expected behavior
Set an object as the state using the return from <MDBSelect getValue()>
Actual behavior
Setting an object as the state triggers an infinite re-render loop. It works normally if a single value is set as the state instead of an object.
Resources (screenshots, code snippets etc.)
import React, { useState } from 'react';
import { MDBSelect } from 'mdb-react-ui-kit';
export default function TestComponent() {
const [obj, setObj] = useState({});
const handleChange = (e) => {
setObj({ foo: e }); // triggers infinite re-render
// this works however: setObj(e);
console.log(obj);
};
return (
<div className='mt-5 d-flex justify-content-center'>
<MDBSelect
data={[
{ text: 'One', value: 1 },
{ text: 'Two', value: 2 },
{ text: 'Three', value: 3 }
]}
getValue={(e) => handleChange(e)}
/>
</div>
);
}
web_ntx
premium answered 11 months ago
Here is a solution for future reference:
import React, { useState, useEffect } from 'react';
import { MDBSelect } from 'mdb-react-ui-kit';
export default function TestComponent() {
const [val, setVal] = useState();
const [obj, setObj] = useState({});
useEffect(() => {
setObj({ text: val });
console.log(val);
}, [val]);
return (
<div className='mt-5 d-flex justify-content-center'>
<MDBSelect
data={[
{ text: 'One', value: 1 },
{ text: 'Two', value: 2 },
{ text: 'Three', value: 3 },
]}
getValue={(foo) => setVal(foo)}
/>
</div>
);
}
Krzysztof Wilk
staff answered 11 months ago
Hi!
Thanks for reporting that. I'm glad you found the solution to that problem. We'll check it and try to fix it as soon as possible :)
Keep coding!
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB React
- MDB Version: MDB5 1.0.0-beta6
- Device: PC
- Browser: Chrome
- OS: Windows 10
- Provided sample code: No
- Provided link: No