I am trying to use react-bootstrap-typeahead in a project. It works as expected when i try it out in an online sandbox (I can expand the drop down and make a selection). When i try to use it in my project, the component is rendered, but clicking on it crashes the page with an error:
react-dom.development.js:24447 Uncaught Error: flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.
Below is the test component i am trying to render which i took from another stack overflow post
import React, { useState } from 'react';
import { Typeahead } from 'react-bootstrap-typeahead';
const MyTypeahead= () => {
const [selected, setSelected] = useState([]);
return (
<div>
<Typeahead
id="basic-typeahead-example"
labelKey="state"
onChange={setSelected}
options={[
{ state: 'AL' },
{ state: 'AK' },
{ state: 'AZ' },
{ state: 'AR' },
{ state: 'CA' },
]}
placeholder="Choose a state..."
selected={selected}
/>
</div>
);
};
export default MyTypeahead;
What's missing? I have a feeling there is some sort of a big gap in my understanding of state management.
Don't pass useState-update function directly in onChange. Instead write a callback and pass it in. Also, in your case, you don't need to use objects in options, just use plain strings:
const MyTypeahead = () => {
const [selected, setSelected] = useState([]);
const handleChange = (selected) => setSelected(selected);
return (
<div>
<Typeahead
id="basic-typeahead-example"
labelKey="state"
onChange={handleChange}
options={["AL", "AK", "AZ", "AR", "CA"]}
placeholder="Choose a state..."
selected={selected}
/>
</div>
);
};
export default MyTypeahead;
https://codesandbox.io/s/adoring-pare-33v6oh
Regarding flushSync - it's a known issue in the repository:
https://github.com/ericgio/react-bootstrap-typeahead/issues/715
Even though the error message is shown, the typeahead component seems to work as it should. I would suggest to ignore this error message until it is been fixed.