From 7c9e5f14a2218eff6b4ffd4c33ecfff22b70cab2 Mon Sep 17 00:00:00 2001 From: Anton Konovalov Date: Wed, 19 Jun 2024 09:42:34 +0300 Subject: [PATCH] Set value on adding setter --- src/factory/createGlobalState.ts | 1 + ...ate.test.ts => createGlobalState.test.tsx} | 22 +++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) rename tests/{createGlobalState.test.ts => createGlobalState.test.tsx} (80%) diff --git a/src/factory/createGlobalState.ts b/src/factory/createGlobalState.ts index c06ba9a085..27ed812e2b 100644 --- a/src/factory/createGlobalState.ts +++ b/src/factory/createGlobalState.ts @@ -35,6 +35,7 @@ export function createGlobalState(initialState?: S) { useIsomorphicLayoutEffect(() => { if (!store.setters.includes(stateSetter)) { store.setters.push(stateSetter); + storeSetter(store.state); } }); diff --git a/tests/createGlobalState.test.ts b/tests/createGlobalState.test.tsx similarity index 80% rename from tests/createGlobalState.test.ts rename to tests/createGlobalState.test.tsx index 6c1945cd77..d6b67b931c 100644 --- a/tests/createGlobalState.test.ts +++ b/tests/createGlobalState.test.tsx @@ -1,5 +1,6 @@ -import { act, renderHook } from '@testing-library/react-hooks'; -import createGlobalState from '../src/factory/createGlobalState'; +import { act, renderHook, render } from '@testing-library/react'; +import React from 'react'; +import createGlobalState from 'src/hooks/createGlobalState'; describe('useGlobalState', () => { it('should be defined', () => { @@ -71,6 +72,23 @@ describe('useGlobalState', () => { }); }); + it('should set ref correctly', async () => { + const useGlobalValue = createGlobalState(); + const CheckComponent = ({ stateValue1 }) => { + const [stateValue2] = useGlobalValue(); + return <>{String(stateValue2 !== undefined && stateValue2 === stateValue1)}; + }; + + const WrapperComponent = () => { + const [stateValue, setStateValue] = useGlobalValue(); + return
+ +
; + }; + const { findByText } = render(); + expect(await findByText('true')).toBeDefined(); + }); + it('initializes with function', () => { const useGlobalValue = createGlobalState(() => 0); const { result: result1 } = renderHook(() => useGlobalValue());