環境・関連リソース
- macOS Catalina 10.15.3
- Node.js v12.14.1
- expo 36.0.0
- react-native-get-random-values 1.3.0
- uuid 7.0.2
uuidを使う
ユニークなランダム ID を生成してくれる uuid を React Native で使おうとすると以下のエラーが発生します。
Error: crypto.getRandomValues() not supported.
↑リンクの指示通り react-native-get-random-values をインストールして uuid の前に import しておきます。
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
...
uuidv4();
アプリをリロードすると、今度は以下のようなエラーが発生します。
Error:TypeError: null is not an object (evaluating 'RNGetRandomValues.getRandomBase64')
こうなると使えないな〜と思い、react-native-uuid に変えてみたらエラーは解消したものの、今度は以下の警告メッセージが発生してしまいます。
警告:[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()
これも使えない!
uuid のエラーを解消して使う
null is not an object エラーを解消するため、16 桁のランダム数字 ( 0 – 255 ) を生成して uuid のシードとして与えます。
// src/utils/uuidSeed.js
export const seed = () => {
const one = Math.floor((Math.random() * 100) / 3.92);
const two = Math.floor((Math.random() * 100) / 3.92);
const three = Math.floor((Math.random() * 100) / 3.92);
const four = Math.floor((Math.random() * 100) / 3.92);
const five = Math.floor((Math.random() * 100) / 3.92);
const six = Math.floor((Math.random() * 100) / 3.92);
const seven = Math.floor((Math.random() * 100) / 3.92);
const eight = Math.floor((Math.random() * 100) / 3.92);
const nine = Math.floor((Math.random() * 100) / 3.92);
const ten = Math.floor((Math.random() * 100) / 3.92);
const eleven = Math.floor((Math.random() * 100) / 3.92);
const twelve = Math.floor((Math.random() * 100) / 3.92);
const thirteen = Math.floor((Math.random() * 100) / 3.92);
const fourteen = Math.floor((Math.random() * 100) / 3.92);
const fifteen = Math.floor((Math.random() * 100) / 3.92);
const sixteen = Math.floor((Math.random() * 100) / 3.92);
return [
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
thirteen,
fourteen,
fifteen,
sixteen
];
};
使い方:
// seed をインポートします。
import "react-native-get-random-values";
import { v4 as uuidv4 } from "uuid";
import { seed } from "../utils/uuidSeed";
// 以下のように使用します。
uuidv4({ random: seed() })
uuidv4({ random: seed() })の実行結果例:
0e0c1207-0f0b-4a17-9309-110c06141608 060a090b-0c03-4900-9506-010b0b010705 0814040d-0413-4805-8217-080d0e000804 09130c13-0d18-4b04-9104-111312020e14
リンク


コメント