Skip to content

Commit

Permalink
Making sure models created with useLocalStore stop updating the state…
Browse files Browse the repository at this point in the history
… on update (#914)

Co-authored-by: Anton Zhuravsky <[email protected]>
  • Loading branch information
yard and yard authored Jul 11, 2024
1 parent 0bbc885 commit 0e7da8d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/use-local-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function useLocalStore(

useEffect(() => {
setCurrentState(store.getState());
store.subscribe(() => {
return store.subscribe(() => {
const nextState = store.getState();
if (currentState !== nextState) {
setCurrentState(nextState);
Expand Down
51 changes: 50 additions & 1 deletion tests/use-local-store.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { render, fireEvent, act } from '@testing-library/react';
import { useLocalStore, action } from '../src';

function CountDisplay() {
Expand Down Expand Up @@ -300,3 +300,52 @@ test('updates the store if a dependency changes', () => {
count: 200,
});
});

test('stops propagating state update when dependencies change', () => {
// ARRANGE
let currentState;
let currentActions;

// eslint-disable-next-line no-shadow, react/prop-types
function CountDisplay({ version }) {
[currentState, currentActions] = useLocalStore(() => ({
count: 0,
up: action((state) => {
state.count = 137;
})
}), [version]);
return null;
}

// ACT
const { rerender } = render(<CountDisplay version={1} />);

// capture action from *current* model instance
const {up} = currentActions;

// ASSERT
expect(currentState).toEqual({
count: 0,
});

// ACT
rerender(<CountDisplay version={2} />);

// ASSERT
expect(currentState).toEqual({
count: 0,
});

// invoke "old" action – since we re-rendered the model it should be no-op
act(() => {
up();
});

// ACT
rerender(<CountDisplay version={2} />);

// ASSERT
expect(currentState).toEqual({
count: 0,
});
});

0 comments on commit 0e7da8d

Please sign in to comment.