Skip to content

Commit

Permalink
feat: check if function component is still mounted before updating th…
Browse files Browse the repository at this point in the history
…e state
  • Loading branch information
atheck committed Aug 26, 2022
1 parent a84942b commit 810e93b
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/useElmish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,14 @@ function useElmish<TProps, TModel, TMessage extends MessageBase> ({ name, props,
let currentModel: Partial<TModel> = {};

const [model, setModel] = useState<Nullable<TModel>>(null);
let initializedModel = model;

const propsRef = useRef(props);
const isMountedRef = useRef(true);

useEffect(() => () => {
isMountedRef.current = false;
}, []);

let initializedModel = model;

if (propsRef.current !== props) {
propsRef.current = props;
Expand Down Expand Up @@ -106,7 +111,7 @@ function useElmish<TProps, TModel, TMessage extends MessageBase> ({ name, props,
}
reentered = false;

if (modified) {
if (isMountedRef.current && modified) {
setModel(prevModel => {
const updatedModel = { ...prevModel as TModel, ...currentModel };

Expand Down

0 comments on commit 810e93b

Please sign in to comment.