bhrott / react-native-masked-text

A pure javascript masked text and input text component for React-Native.
MIT License
1.61k stars 249 forks source link

Two inputs connected problems #214

Closed estevanpedro closed 4 years ago

estevanpedro commented 4 years ago

I have the problem showed below. Both inputs are connected, if i write in one, it will calculate the another one, and vice versa. The problema is, when i type in the 'Quantity of Bitcoin', create a lot of zeros in the TOTAL input. I tried a lot, but couldnt resolve it.

screenshot-web whatsapp com-2019 12 02-16_52_38 (5)

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, TextInput } from 'react-native';
import I18n from '../../i18n/i18n';
import styles from '../../components/Styles';
import { Button3 } from '../../components/Buttons';
import { TextInputMask } from 'react-native-masked-text';

export default function Swap({
  navigation,
  requestBuy,
  requestSell,
  validationSchema,
  pairPrice,
  loading,
  apiErrors,
  bitcoinBalance,
}: {
  navigation: any;
  requestBuy: any;
  requestSell: any;
  validationSchema: any;
  pairPrice: any;
  loading: boolean;
  apiErrors: any;
  bitcoinBalance: string | undefined;
}) {
  // Type: 1 BUY 2 SELL
  const RealToBTC = (value: string, type: number) => {
    if (type !== 1 && type !== 2) return 0; // Invalid type
    return parseFloat(value) / (type === 1 ? pairPrice.buy : pairPrice.sell);
  };

  const BTCToReal = (value: string, type: number) => {
    if (type !== 1 && type !== 2) return 0; // Invalid type
    return parseFloat(value) * (type === 1 ? pairPrice.buy : pairPrice.sell);
  };

  const [wantToSell, setWantToSell] = useState(false);

  const [buyBitcoin, setBuyBitcoin] = useState('');
  const [buyReal, setBuyReal] = useState('');

  const [sellBitcoin, setSellBitcoin] = useState('');
  const [sellReal, setSellReal] = useState('');

  return (
    <View style={{ ...styles.center, backgroundColor: '#1B83E0' }}>
      <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity
          style={{ margin: 15 }}
          onPress={() => {
            setWantToSell(false);
          }}>
          <Text
            style={
              wantToSell
                ? styles.whiteText
                : { ...styles.whiteText, color: '#4caf50' }
            }>
            {I18n.t('toBuy')}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{ margin: 15 }}
          onPress={() => {
            setWantToSell(true);
          }}>
          <Text
            style={
              wantToSell
                ? { ...styles.whiteText, color: '#FF5364' }
                : styles.whiteText
            }>
            {I18n.t('sell')}
          </Text>
        </TouchableOpacity>
      </View>
      {/** ////// */}
      {wantToSell ? (
        <View
          style={{
            width: '86%',
            flex: 1,
            marginTop: 20,
            alignContent: 'center',
          }}>
          <Text
            style={{
              ...styles.whiteText,
              fontSize: 28,
              marginVertical: 20,
              alignSelf: 'center',
            }}>
            {I18n.t('sell')} BTC
          </Text>
          <Text style={{ ...styles.whiteText, fontSize: 20 }}>
            R$ {pairPrice.sell}
          </Text>
          <Text
            style={{ ...styles.whiteText, fontSize: 14, marginVertical: 5 }}>
            {I18n.t('balanceBTC')}: {bitcoinBalance || '...'}
          </Text>
          <View style={{ marginVertical: 20 }}>
            <Text style={styles.Text}>{I18n.t('quantityOfBTC')}</Text>
            <TextInput
              maxLength={10}
              selectionColor={'white'}
              placeholder="Digitar..."
              placeholderTextColor="white"
              style={styles.TextInput2}
              keyboardType="numeric"
              underlineColorAndroid="transparent"
              value={sellBitcoin}
              onChangeText={value => {
                setSellBitcoin(value);
                setSellReal(`${BTCToReal(value, 2)}`);
              }}
            />

            <Text style={styles.Text}>{I18n.t('totalValue')}</Text>
            <TextInputMask
              selectionColor={'white'}
              placeholder={I18n.t('type')}
              placeholderTextColor="white"
              style={styles.TextInput2}
              type={'money'}
              options={{
                precision: 2,
                delimiter: '',
                unit: '',
                suffixUnit: '',
              }}
              value={sellReal}
              onChangeText={value => {
                setSellBitcoin(`${RealToBTC(value.replace(/\./g, ''), 2)}`);
                setSellReal(value.replace(/\./g, ''));
              }}
            />
          </View>

          <TouchableOpacity
            style={{
              alignSelf: 'center',
              width: 193,
              height: 38,
              padding: 8,
              borderRadius: 10,
              alignItems: 'center',
              backgroundColor: '#FF5364',
              marginTop: 20,
            }}
            onPress={() => requestSell(parseFloat(sellBitcoin))}>
            <Text style={styles.textButton}>Vender</Text>
          </TouchableOpacity>
        </View>
      ) : (
        //** */

        //** Compra rápida*/
        <View
          style={{
            width: '86%',
            flex: 1,
            marginTop: 20,
            alignContent: 'center',
          }}>
          <Text
            style={{
              ...styles.whiteText,
              fontSize: 28,
              marginVertical: 20,
              alignSelf: 'center',
            }}>
            {I18n.t('toBuyBTC')}
          </Text>
          <Text style={{ ...styles.whiteText, fontSize: 20 }}>
            R$ {pairPrice.buy}
          </Text>
          <Text
            style={{ ...styles.whiteText, fontSize: 14, marginVertical: 5 }}>
            {I18n.t('balanceBTC')}: {bitcoinBalance || '...'}
          </Text>

          <View style={{ marginVertical: 20 }}>
            <Text style={styles.Text}>{I18n.t('quantityOfBTC')}</Text>
            <TextInput
              maxLength={10}
              selectionColor={'white'}
              placeholder="Digitar..."
              placeholderTextColor="white"
              style={styles.TextInput2}
              keyboardType="numeric"
              underlineColorAndroid="transparent"
              value={buyBitcoin}
              onChangeText={value => {
                setBuyBitcoin(value);
                setBuyReal(`${BTCToReal(value, 2)}`);
              }}
            />

            <Text style={styles.Text}>{I18n.t('totalValue')}</Text>
            <TextInputMask
              selectionColor={'white'}
              placeholder={I18n.t('type')}
              placeholderTextColor="white"
              style={styles.TextInput2}
              type={'money'}
              options={{
                precision: 2,
                delimiter: '',
                unit: '',
                suffixUnit: '',
              }}
              value={buyReal}
              onChangeText={value => {
                setBuyBitcoin(`${RealToBTC(value.replace(/\./g, ''), 2)}`);
                setBuyReal(value.replace(/\./g, ''));
              }}
            />
          </View>

          <TouchableOpacity
            style={{
              alignSelf: 'center',
              width: 193,
              height: 38,
              padding: 8,
              borderRadius: 10,
              alignItems: 'center',
              backgroundColor: '#4caf50',
              marginTop: 20,
            }}
            onPress={() => {
              requestBuy(parseFloat(buyBitcoin));
            }}>
            <Text style={styles.textButton}>Comprar</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}
estevanpedro commented 4 years ago

I solve this problem using .toFixed(2) in the RealToBTC function.