Skip to content

Commit

Permalink
fix: always use latest props in useElmish hook (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
atheck committed Aug 8, 2022
1 parent 44c03e8 commit 9ff4595
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/useElmish.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { Cmd, Dispatch } from "./Cmd";
import { InitFunction, MessageBase, Nullable, UpdateFunction, UpdateMap, UpdateReturnType } from "./Types";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Services } from "./Init";

type SubscriptionResult<TMessage> = [Cmd<TMessage>, (() => void)?];
Expand Down Expand Up @@ -30,6 +30,12 @@ function useElmish<TProps, TModel, TMessage extends MessageBase> ({ name, props,
const [model, setModel] = useState<Nullable<TModel>>(null);
let initializedModel = model;

const propsRef = useRef(props);

if (propsRef.current !== props) {
propsRef.current = props;
}

const execCmd = useCallback((cmd: Cmd<TMessage>): void => {
cmd.forEach(call => {
try {
Expand Down Expand Up @@ -64,7 +70,7 @@ function useElmish<TProps, TModel, TMessage extends MessageBase> ({ name, props,
Services.logger?.debug("Elm", "message from", name, nextMsg);

try {
const [newModel, cmd] = callUpdate(update, nextMsg, { ...initializedModel, ...currentModel }, props);
const [newModel, cmd] = callUpdate(update, nextMsg, { ...initializedModel, ...currentModel }, propsRef.current);

if (modelHasChanged(newModel)) {
currentModel = { ...currentModel, ...newModel };
Expand Down

0 comments on commit 9ff4595

Please sign in to comment.