Skip to content

Commit 860f1a0

Browse files
committed
Should recompute after an element changed
1 parent 66a318a commit 860f1a0

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

packages/api/src/providers/ActivityTyping/private/useReduceActivities.spec.tsx

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,44 @@ describe('setup', () => {
134134
test('should not call fn()', () => expect(fn).toHaveBeenCalledTimes(4));
135135
test('return value should be undefined', () => expect(useReduceActivities).toHaveLastReturnedWith(undefined));
136136
});
137+
138+
describe('when the third activity is being replaced', () => {
139+
let fourthActivity: WebChatActivity;
140+
141+
beforeEach(() => {
142+
fourthActivity = { ...ACTIVITY_TEMPLATE, id: 'a-00004', text: 'Good morning!' };
143+
144+
useActivities.mockImplementationOnce(() => [[firstActivity, fourthActivity, secondActivity]]);
145+
146+
renderResult.rerender(<HookApp fn={fn} />);
147+
});
148+
149+
describe('fn() should have been called', () => {
150+
// It should call 2 more times because the first one should be from cache.
151+
test('6 times in total', () => expect(fn).toHaveBeenCalledTimes(6));
152+
153+
test('with the fourth activity on 5rd call', () =>
154+
expect(fn).toHaveBeenNthCalledWith(
155+
5,
156+
{ maxText: 'Aloha!' },
157+
fourthActivity,
158+
1,
159+
expect.arrayContaining([])
160+
));
161+
162+
test('with the second activity on 6th call', () =>
163+
expect(fn).toHaveBeenNthCalledWith(
164+
6,
165+
{ maxText: 'Good morning!' },
166+
secondActivity,
167+
2,
168+
expect.arrayContaining([])
169+
));
170+
171+
test('return value should be derived from the second activity', () =>
172+
expect(useReduceActivities).toHaveLastReturnedWith({ maxText: 'Hello, World!' }));
173+
});
174+
});
137175
});
138176

139177
describe('when the first activity is removed', () => {

packages/api/src/providers/ActivityTyping/private/useReduceActivities.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,20 @@ export default function useReduceActivities<T>(
1616
(state = Object.freeze([])) => {
1717
let changed = activities.length !== state.length;
1818
let prevValue: T | undefined;
19+
let shouldRecompute = false;
1920

2021
const nextState = activities.map<Entry<T>>((activity, index) => {
2122
const entry = state[+index];
2223

23-
if (Object.is(entry?.activity, activity)) {
24+
if (!shouldRecompute && Object.is(entry?.activity, activity)) {
2425
prevValue = entry?.value;
2526

2627
// Skips the activity if it has been reduced in the past render loop.
2728
return entry;
2829
}
2930

3031
changed = true;
32+
shouldRecompute = true;
3133

3234
return Object.freeze({
3335
activity,

0 commit comments

Comments
 (0)