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

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

React Native カウントアップ処理を実装する

day.js インストール

yarn add dayjs

github.com

day.jsの設定

  • 下記の処理はdayjsを日本時間に設定するための処理
import dayjs from 'dayjs'

// dayjsの タイムゾーンの設定
dayjs.extend(require('dayjs/plugin/timezone'))
dayjs.extend(require('dayjs/plugin/utc'))
dayjs.tz.setDefault('Asia/Tokyo')

カウントアップする処理

  • 下記の2つの関数を利用してカウントアップする処理を実装している
  var countDown = function(){ 
    if (dayjs().diff(currentTime, 'second') >= 20) {
      clearInterval(timer)
      alert('終了')
    }
    setCount(dayjs().diff(currentTime, 'second'))
  };
  
  const stratCountDown = () => {
    // 現在時間を取得する
    currentTime = dayjs()
    // 1秒毎にcountDown関数を呼び出す
    timer = setInterval(countDown, 1000)
  }

全体のコード

  • 下記はボタンクリックした後,20秒後に終了メッセージを表示するサンプルです。
  • 日付の処理はdayjsを利用しています。
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'
import dayjs from 'dayjs'

// dayjsの タイムゾーンの設定
dayjs.extend(require('dayjs/plugin/timezone'))
dayjs.extend(require('dayjs/plugin/utc'))
dayjs.tz.setDefault('Asia/Tokyo')

export const HomeScreen = ( {navigation} ) => {
  const [uuid, setUuid] = useState('')
  const [count, setCount] = useState(0)
  let timer = null
  let currentTime = null

  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)
  }

  var countDown = function(){ 
    if (dayjs().diff(currentTime, 'second') >= 20) {
      clearInterval(timer)
      alert('終了')
    }
    setCount(dayjs().diff(currentTime, 'second'))
  };
  
  const stratCountDown = () => {
    // 現在時間を取得する
    currentTime = dayjs()
    // 1秒毎にcountDown関数を呼び出す
    timer = setInterval(countDown, 1000)
  }

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