Firebase Storage + Vue3/Nuxt3 の罠
下記のようなコードを書いたら、Uncaught (in promise) TypeError: Cannot set properties of null (setting 'value')
というエラーがでました。
storage.vue
<script setup>
import { getStorage, ref} from "firebase/storage";
....
const file = ref();
....
onMounted(()=>{
const storage = getStorage();
fire.value = ref(storage, 'hoge/foo.dat');
// 上の行で Uncaught (in promise) TypeError: Cannot set properties of null (setting 'value') というエラーが出る
....
})
</script>
結論から言えば、firebase storage の ref
関数を import したことで、vue3 の ref
関数が上書きされてしまっていたせいでした。
一見、すぐにわかりそうなものですが、コードが上の例ほどすっきりしていない状態で、なおかつ nuxt3 だと ref
は明示的に import しなくても良いこともあって、気が付くまでかなりの時間を要しました。
対策
import { exportA as aliasA } from '....'
で ref
に別名を与えることで解決できます。
storage.vue
<script setup>
import { getStorage, ref as storageRef} from "firebase/storage";
const file = ref();
....
onMounted(()=>{
const storage = getStorage();
fire.value = storageRef(storage, 'hoge/foo.dat');
....
})
</script>
firebase 関連の関数名は、何気に短いものが多いので(forestore の doc
とか)、忘れたころに同じような目にあう可能性が高そうです。エラーだけ見ても理由が分からないところが罠ですね・・・。
関数名が短いものは別名を付けて import するようにしたほうがいいかもしれません。