Closed2
React Native(Expo Go) で SWR の useSWRMutation がエラーになる件

React Native で swr を使っていると Mutation の hook を呼んだ時に以下のようにエラーになるので、解消するためのメモ。手元の動作では、isMutating
を使っているとエラーになるぽく data
のみの利用だとエラーが出なかった。
TypeError: Cannot read property 'add' of undefined
環境
expo: 52.0.35
react: 18.3.1
react-native: 0.76.7
swr: 2.2.5
expo の newArchtecture は有効になっている
app.json
{
"expo": {
"newArchEnabled": true,
}
}
Issue

Issue にパッチの該当箇所が書いてあるので、手元でも修正する。
今回は pnpm でパッチする。
-
pnpm patch swr
を実行 - 編集用のファイルが作成されるので、
swr/dist/mutation/index.js
を以下のように編集
// NOTE: エラーになる startTransition をコメントアウト
// https://github.com/vercel/swr/issues/2986
// const startTransition = index_js.IS_REACT_LEGACY ? (cb)=>{
// cb();
// } : React__default.default.startTransition;
...
const mutation = ()=>(key, fetcher, config = {})=>{
const [, startTransition] = React.useTransition() // React からインポートした startTransition を代わりに配置
-
pnpm patch-commit {編集したパッケージのパス}
でパッチを適用 -
patches/swr.patch
が作成されることを確認
diff --git a/dist/mutation/index.js b/dist/mutation/index.js
index 1c5d31bcc2ffa549b53a273b653b8fda2cb7ff11..42bb31fc7bdce4ee03f1de4fe14e9db8c7df8684 100644
--- a/dist/mutation/index.js
+++ b/dist/mutation/index.js
@@ -9,9 +9,11 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var React__default = /*#__PURE__*/_interopDefault(React);
var useSWR__default = /*#__PURE__*/_interopDefault(useSWR);
-const startTransition = index_js.IS_REACT_LEGACY ? (cb)=>{
- cb();
-} : React__default.default.startTransition;
+// NOTE: comment out this function because of below issue
+// https://github.com/vercel/swr/issues/2986
+// const startTransition = index_js.IS_REACT_LEGACY ? (cb)=>{
+// cb();
+// } : React__default.default.startTransition;
/**
* An implementation of state with dependency-tracking.
* @param initialState - The initial state object.
@@ -82,6 +84,7 @@ const startTransition = index_js.IS_REACT_LEGACY ? (cb)=>{
};
const mutation = ()=>(key, fetcher, config = {})=>{
+ const [, startTransition] = React.useTransition()
const { mutate } = useSWR.useSWRConfig();
const keyRef = React.useRef(key);
const fetcherRef = React.useRef(fetcher);
このスクラップは2ヶ月前にクローズされました
ログインするとコメントできます