フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

ReactNativeでUUIDを生成する

インストール

yarn add react-native-uuid
expo install expo-random
expo install expo-crypto

参考URL

github.com

docs.expo.io

docs.expo.io

サンプルコード

import React, { useState, useEffect } from "react";
import { ScrollView,Button, View, Text } from 'react-native';
import * as Random from 'expo-random';
import * as Crypto from 'expo-crypto';

export const HomeScreen = ( {navigation} ) => {
  const [uuid, setUuid] = useState('');

  useEffect(() => {
    cryptoDigestStringAsync(stringNumber())
  }, []);  

   // 乱数生成
   const stringNumber = () => {
    return Random.getRandomBytes(32).reduce((accumulator, value) => {
      if (accumulator !== undefined) {
        return String(accumulator) + String(value)
      } else {
        return String(value)
      }
    })
  }
  // 暗号化する関数
  const cryptoDigestStringAsync = async (value)=>{
    var uuid = require('react-native-uuid');
    const digest = await Crypto.digestStringAsync(
      Crypto.CryptoDigestAlgorithm.SHA256,
      uuid + value  // 生成した乱数 + react-native-uuidで取得した文字列を組み合わせ ユニーク値を生成する
    );
    setUuid(digest)
  }

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <View style={{width: "100%", backgroundColor: '#40e0d0'}}>
          <Text>Hedar</Text>
        </View>      
        <ScrollView>          
          <Text>テストテストテストテストテスト </Text>
          <Text>{ uuid }</Text>
          <Button
            title="次の画面へ"
            onPress={() => navigation.navigate('Details')}
          />
        </ScrollView>
        <View style={{width: "100%", backgroundColor: '#9370db'}}>
          <Text>フッター</Text>
        </View>      
     </View>
  );
}

実行結果

f:id:PX-WING:20210129202819j:plain