Skip to content

Commit

Permalink
fix: fix error of useFlag$ in ssr (#37)
Browse files Browse the repository at this point in the history
* fix(useserialrequest): show loading when partial requests hit cache

* fix(ssr): fix error of useFlag$ in ssr

fix alovajs/alova#186
  • Loading branch information
JOU-amjs authored Aug 21, 2023
1 parent 96328c2 commit 722006b
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 83 deletions.
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export default {
},

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
transformIgnorePatterns: ['/node_modules/(?!(alova|@alova\\/mock)/)']
transformIgnorePatterns: ['/node_modules/(?!(alova|@alova/mock))']

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
Expand Down
20 changes: 10 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"@typescript-eslint/eslint-plugin": "^5.43.0",
"@typescript-eslint/parser": "^5.43.0",
"@vue/vue3-jest": "^29.2.4",
"alova": "^2.10.1",
"alova": "^2.11.0",
"babel-jest": "^29.2.2",
"commitizen": "^4.3.0",
"commitlint": "^17.5.1",
Expand Down
22 changes: 9 additions & 13 deletions src/framework/react.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isArray, isFn, isObject, map, noop, pushItem } from '@/helper';
import { falseValue, undefinedValue } from '@/helper/variables';
import { falseValue } from '@/helper/variables';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';

/**
Expand All @@ -13,7 +13,7 @@ export const $ = (initialState, isRef) => {
const state = useState(initialState);
if (isRef) {
const ref = useFlag$();
ref.v = state[0];
ref.current = state[0];
state[2] = ref; // 将引用值保存到数组中
}
return state;
Expand All @@ -32,7 +32,7 @@ export const $$ = (factory, deps, isRef) => {
const memoAry = [memo, noop];
if (isRef) {
const ref = useFlag$();
ref.v = memo;
ref.current = memo;
pushItem(memoAry, ref);
}
return memoAry;
Expand All @@ -46,7 +46,7 @@ export const $$ = (factory, deps, isRef) => {
*/
export const _$ = state => {
if (isArray(state) && isFn(state[1])) {
return state[2] ? state[2].v : state[0];
return state[2] ? state[2].current : state[0];
}
return state;
};
Expand All @@ -73,14 +73,14 @@ export const _expBatch$ = (...states) => map(states, s => _exp$(s));
*/
export const upd$ = (state, newData) => {
if (isFn(newData)) {
const oldState = state[2] ? state[2].v : state[0];
const oldState = state[2] ? state[2].current : state[0];
newData = newData(isArray(oldState) ? [...oldState] : isObject(oldState) ? { ...oldState } : oldState);
}
state[1](newData);

// 如果有引用类型值,也要更新它
if (state[2]) {
state[2].v = newData;
state[2].current = newData;
}
};

Expand Down Expand Up @@ -109,11 +109,7 @@ export const onMounted$ = cb => useEffect(cb, []);
* 为解决这个问题,在react中需使用useRef作为标识
* @param initialValue 初始值
*/
export const useFlag$ = initialValue => {
const ref = useRef(initialValue);
ref.v === undefinedValue && (ref.v = initialValue);
return ref;
};
export const useFlag$ = initialValue => useRef(initialValue);

/**
* 将alova的hook返回状态如loading、data等转换为不受闭包陷阱影响的值
Expand All @@ -124,7 +120,7 @@ export const useFlag$ = initialValue => {
export const useRequestRefState$ = requestState => {
const requestStateWrapper = [requestState, noop];
const ref = useFlag$();
ref.v = requestState;
ref.current = requestState;
pushItem(requestStateWrapper, ref);
return requestStateWrapper;
};
Expand All @@ -136,7 +132,7 @@ export const useRequestRefState$ = requestState => {
*/
export const useMemorizedCallback$ = callback => {
const ref = useFlag$();
ref.v = callback;
ref.current = callback;
return useCallback((...args) => {
callback.apply(null, args);
}, []);
Expand Down
4 changes: 2 additions & 2 deletions src/framework/svelte.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { __self, createSyncOnceRunner, isFn, map } from '@/helper';
import { createSyncOnceRunner, isFn, map, __self } from '@/helper';
import { falseValue, trueValue, undefinedValue } from '@/helper/variables';
import { onMount } from 'svelte';
import { derived, writable } from 'svelte/store';
Expand Down Expand Up @@ -87,7 +87,7 @@ export const onMounted$ = cb => {
* 兼容react
* @param initialValue 初始值
*/
export const useFlag$ = initialValue => ({ v: initialValue });
export const useFlag$ = initialValue => ({ current: initialValue });

/**
* 由于在react下,use hook返回的loading、data等状态为普遍值,将会受闭包影响
Expand Down
2 changes: 1 addition & 1 deletion src/framework/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export type TonMounted$ = (cb: () => void) => void;
* 兼容react
* @param initialValue 初始值
*/
export type TuseFlag$ = <T>(initialValue: T) => { v: T };
export type TuseFlag$ = <T>(initialValue: T) => { current: T };

/**
* 将alova的hook返回状态如loading、data等转换为不受闭包陷阱影响的值
Expand Down
6 changes: 3 additions & 3 deletions src/framework/vue.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { __self, isFn, map } from '@/helper';
import { isFn, map, __self } from '@/helper';
import { trueValue } from '@/helper/variables';
import { computed, ref, onMounted as vueOnMounted, watch as vueWatch } from 'vue';
import { computed, onMounted as vueOnMounted, ref, watch as vueWatch } from 'vue';

/**
* 创建状态
Expand Down Expand Up @@ -69,7 +69,7 @@ export const onMounted$ = cb => {
* 兼容react
* @param initialValue 初始值
*/
export const useFlag$ = initialValue => ({ v: initialValue });
export const useFlag$ = initialValue => ({ current: initialValue });

/**
* 由于在react下,use hook返回的loading、data等状态为普遍值,将会受闭包影响
Expand Down
29 changes: 15 additions & 14 deletions src/hooks/pagination/usePagination.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,15 @@ export default function (
const pageSize = $(initialPageSize, trueValue);
const data = $([], trueValue);
const handerRef = useFlag$();
handerRef.v = handler;
handerRef.current = handler;

// 保存当前hook所使用到的所有method实例快照
const {
snapshots: methodSnapshots,
get: getSnapshotMethods,
save: saveSnapshot,
remove: removeSnapshot
} = useFlag$(createSnapshotMethodsManager(page => handerRef.v(page, _$(pageSize)))).v;
} = useFlag$(createSnapshotMethodsManager(page => handerRef.current(page, _$(pageSize)))).current;

const listDataGetter = rawData => dataGetter(rawData) || rawData;
const getHandlerMethod = (refreshPage = _$(page)) => {
Expand All @@ -86,7 +86,7 @@ export default function (
// 监听状态变化时,重置page为1
watch$(watchingStates, () => {
upd$(page, 1);
isReset.v = trueValue;
isReset.current = trueValue;
});

// 兼容react,将需要代理的函数存放在此
Expand All @@ -95,11 +95,12 @@ export default function (
const createDelegationAction =
actionName =>
(...args) =>
delegationActions.v[actionName](...args);
delegationActions.current[actionName](...args);
const states = useWatcher(getHandlerMethod, [...watchingStates, _exp$(page), _exp$(pageSize)], {
immediate,
initialData,
debounce,
abortLast: falseValue,
middleware(ctx, next) {
middleware(
{
Expand Down Expand Up @@ -128,10 +129,10 @@ export default function (

// 监听值改变时将会重置为第一页,此时会触发两次请求,在这边过滤掉一次请求
let requestPromise = promiseResolve();
if (!isReset.v) {
if (!isReset.current) {
requestPromise = next();
} else if (requestCountInReseting.v === 0) {
requestCountInReseting.v++;
} else if (requestCountInReseting.current === 0) {
requestCountInReseting.current++;
requestPromise = next();
}
return requestPromise;
Expand Down Expand Up @@ -260,7 +261,7 @@ export default function (
// 如果追加数据,才更新data
if (append) {
// 如果是reset则先清空数据
isReset.v && upd$(data, []);
isReset.current && upd$(data, []);
if (refreshPage === undefinedValue) {
upd$(data, [..._$(data), ...listData]);
} else if (refreshPage) {
Expand All @@ -273,8 +274,8 @@ export default function (
} else {
upd$(data, listData);
}
isReset.v = falseValue;
requestCountInReseting.v = 0;
isReset.current = falseValue;
requestCountInReseting.current = 0;
});

// 获取列表项所在位置
Expand Down Expand Up @@ -307,7 +308,7 @@ export default function (
}
});

const removeSyncRunner = useFlag$(createSyncOnceRunner()).v;
const removeSyncRunner = useFlag$(createSyncOnceRunner()).current;
// 删除除此usehook当前页和下一页的所有相关缓存
const invalidatePaginationCache = (all = falseValue) => {
const pageVal = _$(page);
Expand Down Expand Up @@ -338,7 +339,7 @@ export default function (

// 单独拿出来的原因是
// 无论同步调用几次insert、remove,或它们组合调用,reset操作只需要异步执行一次
const resetSyncRunner = useFlag$(createSyncOnceRunner()).v;
const resetSyncRunner = useFlag$(createSyncOnceRunner()).current;
const resetCache = () =>
resetSyncRunner(() => {
_$(fetchingRef) && abortFetch();
Expand Down Expand Up @@ -493,12 +494,12 @@ export default function (
*/
const reload = useMemorizedCallback$(() => {
invalidatePaginationCache(trueValue);
isReset.v = trueValue;
isReset.current = trueValue;
_$(page) === 1 ? send() : upd$(page, 1);
});

// 兼容react,每次缓存最新的操作函数,避免闭包陷阱
delegationActions.v = {
delegationActions.current = {
refresh,
insert,
remove,
Expand Down
8 changes: 4 additions & 4 deletions src/hooks/useCaptcha.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { T$, T_$, T_exp$, Tupd$, TuseFlag$, TuseMemorizedCallback$ } from '@/framework/type';
import { T$, Tupd$, TuseFlag$, TuseMemorizedCallback$, T_$, T_exp$ } from '@/framework/type';
import { buildErrorMsg, createAssert, newInstance } from '@/helper';
import { PromiseCls, falseValue, trueValue, undefinedValue } from '@/helper/variables';
import { falseValue, PromiseCls, trueValue, undefinedValue } from '@/helper/variables';
import { AlovaMethodHandler, Method, useRequest } from 'alova';
import { CaptchaHookConfig } from '~/typings/general';

Expand Down Expand Up @@ -34,10 +34,10 @@ export default <S, E, R, T, RC, RE, RH>(
.send(...args)
.then(result => {
upd$(countdown, config.initialCountdown || 60);
timer.v = setInterval(() => {
timer.current = setInterval(() => {
upd$(countdown, val => val - 1);
if (_$(countdown) <= 0) {
clearInterval(timer.v);
clearInterval(timer.current);
}
}, 1000);
resolve(result);
Expand Down
18 changes: 9 additions & 9 deletions src/hooks/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ export default <S, E, R, T, RC, RE, RH, F>(
* 重置form数据
*/
const reset = useMemorizedCallback$(() => {
reseting.v = trueValue;
reseting.current = trueValue;
upd$(form, cloneFormData(initialForm));
enableStore && storageContext.remove(storagedKey.v);
enableStore && storageContext.remove(storagedKey.current);
});

/**
Expand Down Expand Up @@ -138,11 +138,11 @@ export default <S, E, R, T, RC, RE, RH, F>(
if (id) {
// 还没有共享状态则表示当前hook是创建的hook
if (!sharedState) {
isCreateShardState.v = trueValue;
isCreateShardState.current = trueValue;
}

// 只保存创建hook的共享状态
if (isCreateShardState.v) {
if (isCreateShardState.current) {
sharedStates[id] = {
hookReturns,
config
Expand All @@ -156,7 +156,7 @@ export default <S, E, R, T, RC, RE, RH, F>(
if (enableStore && !sharedState) {
// 获取存储并更新data
// 需要在onMounted中调用,否则会导致在react中重复被调用
const storagedForm = serializerPerformer.v.deserialize(storageContext.get(storagedKey.v));
const storagedForm = serializerPerformer.current.deserialize(storageContext.get(storagedKey.current));

// 有草稿数据时,异步恢复数据,否则无法正常绑定onRetore事件
if (storagedForm) {
Expand All @@ -170,11 +170,11 @@ export default <S, E, R, T, RC, RE, RH, F>(

// 监听变化同步存储,如果是reset触发的则不需要再序列化
watch$([form], () => {
if (reseting.v || !enableStore) {
reseting.v = falseValue;
if (reseting.current || !enableStore) {
reseting.current = falseValue;
return;
}
storageContext.set(storagedKey.v, serializerPerformer.v.serialize(_$(form)));
storageContext.set(storagedKey.current, serializerPerformer.current.serialize(_$(form)));
});
// 如果在提交后需要清除数据,则调用reset
onSuccess(() => {
Expand All @@ -183,5 +183,5 @@ export default <S, E, R, T, RC, RE, RH, F>(

// 有已保存的sharedState,则返回它
// 如果是当前hook创建的共享状态,则返回最新的而非缓存的
return sharedState && !isCreateShardState.v ? sharedState.hookReturns : hookReturns;
return sharedState && !isCreateShardState.current ? sharedState.hookReturns : hookReturns;
};
Loading

0 comments on commit 722006b

Please sign in to comment.