native-base#Spinner JavaScript Examples

The following examples show how to use native-base#Spinner. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From puente-reactnative-collect with MIT License 5 votes vote down vote up
Geolocation = ({ errors, formikKey, setFieldValue }) => {
  const [location, setLocation] = useState({ latitude: 0, longitude: 0, altitude: 0 });
  const [locationLoading, setLocationLoading] = useState(false);
  const [submissionError, setSubmissionError] = useState(false);

  const handleLocation = async () => {
    setLocationLoading(true);

    const locationPromise = new Promise((resolve, reject) => {
      try {
        return getLocation().then((value) => resolve(value));
      } catch (e) {
        return reject(e);
      }
    });

    const currentLocation = await fulfillWithTimeLimit(20000, locationPromise, null);

    if (!currentLocation) {
      setFieldValue('location', { latitude: 0, longitude: 0, altitude: 0 });
      setLocationLoading(false);
      setSubmissionError(true);
    } else {
      const { latitude, longitude, altitude } = currentLocation.coords;
      setFieldValue('location', { latitude, longitude, altitude });
      setLocation({ latitude, longitude, altitude });
      setLocationLoading(false);
    }
  };
  return (
    <View key={formikKey}>
      {location === null && (
      <PaperButton
        onPressEvent={handleLocation}
        buttonText={I18n.t('paperButton.getLocation')}
      />
      )}
      {location !== null && (
      <View>
        <PaperButton
          onPressEvent={handleLocation}
          buttonText={I18n.t('paperButton.getLocationAgain')}
        />
        <View style={{ marginLeft: 'auto', marginRight: 'auto', flexDirection: 'row' }}>
          {
            locationLoading === true
            && <Spinner color={theme.colors.primary} />
          }
          {locationLoading === false
            && (
              <View>
                <Headline>
                  {`(${location.latitude.toFixed(2)}, ${location.longitude.toFixed(2)})`}
                </Headline>
              </View>
            )}
        </View>
        <Text style={{ color: 'red' }}>
          {errors[formikKey]}
        </Text>
      </View>
      )}
      <PopupError
        error={submissionError}
        setError={setSubmissionError}
        errorMessage="submissionError.geolocation"
      />
    </View>
  );
}
Example #2
Source File: MakeTransaction.js    From web3-react-native with MIT License 4 votes vote down vote up
MakeTransaction = ({ onPressSubmit, ...extraProps }) => {
  const [toAddress, setToAddress] = useState("0x19e03255f667bdfd50a32722df860b1eeaf4d635");
  const [amount, setAmount] = useState("1");
  const [units, setUnits] = useState("wei");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  return (
    <Container>
      <Content>
        <Form>
          <Item>
            <Label
              children="Address:"
            />
            <Input
              onChangeText={setToAddress}
              value={toAddress}
            />
          </Item>
          <Item
          >
            <Label
              children="Amount:"
            />
            <Input
              onChangeText={setAmount}
              value={amount}
            />
          </Item>
          <Item
            last
          >
            <Label
              children="Units:"
            />
            <Picker
              onValueChange={setUnits}
              selectedValue={units}
            >
              <Picker.Item label="Wei" value="wei" />
              <Picker.Item label="Kwei" value="kwei" />
              <Picker.Item label="Mwei" value="mwei" />
              <Picker.Item label="Gwei" value="gwei" />
              <Picker.Item label="Finney" value="finney" />
              <Picker.Item label="Ether" value="eth" />
            </Picker>
          </Item>
        </Form>
        <View
          style={styles.errorContainer}
        >
          {(!!error) && (
            <Text
              style={styles.error}
              children={error.message}
            />
          )} 
        </View>
        <View
          style={styles.buttonContainer}
        >
          <Button
            disabled={loading}
            style={styles.button}
            onPress={e => Promise
              .resolve()
              .then(() => [
                setLoading(true),
              ])
              .then(() => onPressSubmit(e, toAddress, amount, units))
              .then(() => setLoading(false))
              .catch(
                (e) => {
                  setError(e);
                  setLoading(false);
                },
              )}
            primary
            rounded
          >
            {(!!loading) && (
              <Spinner
                size={20}
              />
            )}
            <Text
              children="Send"
            />
          </Button>
        </View>
      </Content>
    </Container>
  );
}
Example #3
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
AssetSearchbar = ({ setSelectedAsset, surveyingOrganization }) => {
  const [query, setQuery] = useState('');
  const [assetData, setAssetData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [online, setOnline] = useState(true);
  const [searchTimeout, setSearchTimeout] = useState(null);

  useEffect(() => {
    checkOnlineStatus().then(async (connected) => {
      if (connected) fetchData(true, '');
      if (!connected) fetchData(false, '');
    });
  }, [surveyingOrganization]);

  // remove this offline portion if he says no offline
  const fetchOfflineData = async () => {
    setOnline(false);

    await getData('assetData').then(() => {
      if (assetData) {
        let offlineData = [];
        getData('offlineAssetIDForms').then((offlineAssetData) => {
          if (offlineAssetData !== null) {
            Object.entries(offlineAssetData).forEach(([key, value]) => { //eslint-disable-line
              offlineData = offlineData.concat(value.localObject);
            });
          }
          const allData = assetData.concat(offlineData);
          setAssetData(allData.slice() || []);
        });
      }
      setLoading(false);
    });
  };

  const fetchOnlineData = async () => {
    setOnline(true);

    assetDataQuery(surveyingOrganization).then((records) => {
      let offlineData = [];

      getData('offlineAssetIDForms').then((offlineAssetData) => {
        if (offlineAssetData !== null) {
          Object.entries(offlineAssetData).forEach(([key, value]) => { //eslint-disable-line
            offlineData = offlineData.concat(value.localObject);
          });
        }
      });

      const allData = records.concat(offlineData);
      setAssetData(allData.slice());
      setLoading(false);
    });
  };

  const fetchData = (onLine, qry) => {
    // remove this line if no offline too - 82
    if (!onLine) fetchOfflineData();
    if (onLine) fetchOnlineData(qry);
  };

  // probably not needed, this is all specific to the id form
  const filterOfflineList = () => assetData.filter(
    (listItem) => {
      // const listItemJSON = listItem.toJSON();
      const name = listItem.name || ' ';
      return name.toLowerCase().includes(query.toLowerCase());
    }
  );

  const onChangeSearch = (input) => {
    setLoading(true);

    if (input === '') setLoading(false);

    clearTimeout(searchTimeout);

    setQuery(input);

    setSearchTimeout(setTimeout(() => {
      fetchData(online, input);
    }, 1000));
  };

  const onSelectAsset = (listItem) => {
    setSelectedAsset(listItem);
    setQuery('');
  };

  const renderItem = ({ item }) => (
    <View>
      <Button onPress={() => onSelectAsset(item)} contentStyle={{ marginRight: 5 }}>
        <Text style={{ marginRight: 10 }}>{item.name}</Text>

        <View style={{
          backgroundColor: '#f8380e',
          width: 1,
          height: 10,
          paddingLeft: 10,
          marginTop: 'auto',
          marginBottom: 'auto',
          borderRadius: 20
        }}
        />
      </Button>
    </View>
  );

  return (
    <View>
      <Headline style={styles.header}>{I18n.t('assetSearchbar.searchIndividual')}</Headline>
      <Searchbar
        placeholder={I18n.t('assetSearchbar.placeholder')}
        onChangeText={onChangeSearch}
        value={query}
      />
      {!online
        && <Button onPress={() => fetchData(false, '')}>{I18n.t('global.refresh')}</Button>}
      {loading
        && <Spinner color="blue" />}
      {query !== '' && (
        <FlatList
          data={filterOfflineList(assetData)}
          renderItem={renderItem}
          keyExtractor={(item) => item.objectId}
        />
      )}
    </View>
  );
}
Example #4
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
FindResidents = ({
  selectPerson, setSelectPerson, organization, puenteForms, navigateToNewRecord,
  surveyee, setSurveyee, setView
}) => {
  const [query, setQuery] = useState('');
  const [residentsData, setResidentsData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [online, setOnline] = useState(true);
  const [searchTimeout, setSearchTimeout] = useState(null);
  const { residentOfflineData } = useContext(OfflineContext);

  useEffect(() => {
    checkOnlineStatus().then(async (connected) => {
      if (connected) fetchData(true, '');
      if (!connected) fetchData(false, '');
    });
  }, [organization]);

  const fetchOfflineData = () => {
    setOnline(false);
    return residentOfflineData().then((residents) => {
      setResidentsData(residents);
      setLoading(false);
    });
  };

  const fetchOnlineData = async (qry) => {
    setOnline(true);

    const records = await parseSearch(organization, qry);

    let offlineData = [];

    await getData('offlineIDForms').then((offlineResidentData) => {
      if (offlineResidentData !== null) {
        Object.entries(offlineResidentData).forEach(([key, value]) => { //eslint-disable-line
          offlineData = offlineData.concat(value.localObject);
        });
      }
    });

    const allData = records.concat(offlineData);
    setResidentsData(allData.slice());
    setLoading(false);
  };

  const fetchData = (onLine, qry) => {
    if (!onLine) fetchOfflineData();
    if (onLine) fetchOnlineData(qry);
  };

  const filterOfflineList = () => residentsData.filter(
    (listItem) => {
      const fname = listItem.fname || ' ';
      const lname = listItem.lname || ' ';
      const nickname = listItem.nickname || ' ';
      return fname.toLowerCase().includes(query.toLowerCase())
        || lname
          .toLowerCase()
          .includes(query.toLowerCase())
        || `${fname} ${lname}`
          .toLowerCase()
          .includes(query.toLowerCase())
        || nickname
          .toLowerCase()
          .includes(query.toLowerCase());
    }
  );

  const onChangeSearch = (input) => {
    setLoading(true);

    if (input === '') setLoading(false);

    clearTimeout(searchTimeout);

    setQuery(input);

    setSearchTimeout(setTimeout(() => {
      fetchData(online, input);
    }, 1000));
  };

  const onSelectPerson = (listItem) => {
    setSelectPerson(listItem);
    setQuery('');
  };

  const renderItem = ({ item }) => (
    <View key={item.objectId}>
      <ResidentCard
        resident={item}
        onSelectPerson={onSelectPerson}
      />
    </View>
  );

  return (
    <View>
      <View style={styles.container}>
        {!selectPerson && (
          <>
            <Headline style={styles.header}>{I18n.t('findResident.searchIndividual')}</Headline>
            <Searchbar
              placeholder={I18n.t('findResident.typeHere')}
              onChangeText={onChangeSearch}
              value={query}
            />
          </>
        )}

        {!online
          && <Button onPress={() => fetchData(false, '')}>{I18n.t('global.refresh')}</Button>}
        {loading
          && <Spinner color="blue" />}

        {!selectPerson
          && (
            <FlatList
              data={online ? residentsData : filterOfflineList(residentsData)}
              renderItem={renderItem}
              keyExtractor={(item) => item.objectId}
            />
          )}
      </View>

      {selectPerson && (
        <ResidentPage
          fname={selectPerson.fname}
          lname={selectPerson.lname}
          nickname={selectPerson.nickname}
          city={selectPerson.city}
          license={selectPerson.license}
          picture={selectPerson.picture}
          selectPerson={selectPerson}
          setSelectPerson={setSelectPerson}
          puenteForms={puenteForms}
          navigateToNewRecord={navigateToNewRecord}
          surveyee={surveyee}
          setSurveyee={setSurveyee}
          setView={setView}
        />
      )}
    </View>
  );
}
Example #5
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
FormCounts = ({ setShowCounts }) => {
  const [surveyCount, setSurveyCount] = useState(0);
  const [envHealthCount, setEnvHealthCount] = useState(0);
  const [vitalsCount, setVitalsCount] = useState(0);
  const [customCount, setCustomCount] = useState(0);
  const [assetCount, setAssetCount] = useState(0);
  const [userName, setUserName] = useState(' ');
  const [error, setError] = useState(false);
  const [offline, setOffline] = useState(false);

  const [queryDone, setQueryDone] = useState(false);

  useEffect(() => {
    getData('currentUser').then((user) => {
      const username = `${user.firstname || ''} ${user.lastname || ''}`;
      setUserName(username);
    });
  }, []);

  useEffect(() => {
    const postParamsSurvey = {
      ParseClass: 'SurveyData',
      parseColumn: 'surveyingUser',
      parseParam: userName
    };
    const postParamsEnvHealth = {
      ParseClass: 'HistoryEnvironmentalHealth',
      parseColumn: 'surveyingUser',
      parseParam: userName
    };
    const postParamsVitals = {
      ParseClass: 'Vitals',
      parseColumn: 'surveyingUser',
      parseParam: userName
    };
    const postParamsCustomForms = {
      ParseClass: 'FormResults',
      parseColumn: 'surveyingUser',
      parseParam: userName
    };
    const postParamsAssets = {
      ParseClass: 'FormResults',
      parseColumn: 'surveyingUser',
      parseParam: userName
    };

    const idPromise = countService(postParamsSurvey);
    const envHealthPromise = countService(postParamsEnvHealth);
    const vitalsPromise = countService(postParamsVitals);
    const customFormsPromise = countService(postParamsCustomForms);
    const assetPromise = countService(postParamsAssets);

    checkOnlineStatus().then(async (connected) => {
      if (connected) {
        Promise.all([idPromise, envHealthPromise,
          vitalsPromise, customFormsPromise,
          assetPromise]).then((values) => {
          setSurveyCount(values[0]);
          setEnvHealthCount(values[1]);
          setVitalsCount(values[2]);
          setCustomCount(values[3]);
          setAssetCount(values[4]);
          setQueryDone(true);
        }, () => {
          // error - maybe inform user
          setError(true);
        });
      } else {
        setOffline(true);
      }
    });
  }, [userName]);

  return (
    <View>
      <Text style={styles.headerFormText}>{I18n.t('formCounts.surveysCollected')}</Text>
      <View style={styles.horizontalLineGray} />
      {error && (
      <View>
        <Text style={styles.label}>
          f
          {I18n.t('formCounts.error')}
        </Text>
      </View>
      )}
      {offline && (
      <View>
        <Text style={styles.label}>{I18n.t('formCounts.offline')}</Text>
      </View>
      )}
      {queryDone && (
      <View>
        <View style={styles.countContainer}>
          <Text style={styles.label}>{I18n.t('formCounts.idForms')}</Text>
          <Text style={styles.count}>{surveyCount}</Text>
        </View>
        <View style={styles.horizontalLineGray} />
        <View style={styles.countContainer}>
          <Text style={styles.label}>{I18n.t('formCounts.envHealthForms')}</Text>
          <Text style={styles.count}>{envHealthCount}</Text>
        </View>
        <View style={styles.horizontalLineGray} />
        <View style={styles.countContainer}>
          <Text style={styles.label}>{I18n.t('formCounts.vitalsForms')}</Text>
          <Text style={styles.count}>{vitalsCount}</Text>
        </View>
        <View style={styles.horizontalLineGray} />
        <View style={styles.countContainer}>
          <Text style={styles.label}>{I18n.t('formCounts.customForms')}</Text>
          <Text style={styles.count}>{customCount}</Text>
        </View>
        <View style={styles.horizontalLineGray} />
        <View style={styles.countContainer}>
          <Text style={styles.label}>{I18n.t('formCounts.assetForms')}</Text>
          <Text style={styles.count}>{assetCount}</Text>
        </View>
        <View style={styles.horizontalLineGray} />
      </View>
      )}
      {!queryDone && !error && !offline && (
      <Spinner color={theme.colors.primary} />
      )}
      <Button onPress={() => setShowCounts(false)}>{I18n.t('formCounts.back')}</Button>
    </View>
  );
}
Example #6
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
Header = ({
  setSettings
}) => {
  const { header, headerText, headerIcon } = styles;
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [volunteerDate, setVolunteerDate] = useState('');
  const [volunteerGreeting, setVolunteerGreeting] = useState('');
  const [offlineForms, setOfflineForms] = useState(false);
  const [offlineFormCount, setOfflineFormCount] = useState(0);
  const [submission, setSubmission] = useState(null);
  const [showCounts, setShowCounts] = useState(false);
  const { populateResidentDataCache, isLoading: isOfflineLoading } = useContext(OfflineContext);

  const volunteerLength = (object) => {
    const date = new Date(object.createdAt);
    const convertedDate = date.toDateString();
    return convertedDate;
  };

  const calculateTime = (name) => {
    const today = new Date();
    const curHr = today.getHours();

    if (curHr < 12) {
      setVolunteerGreeting(`${I18n.t('header.goodMorning')} ${name}!` || I18n.t('header.goodMorning!'));
    } else if (curHr < 18) {
      setVolunteerGreeting(`${I18n.t('header.goodAfternoon')} ${name}!` || I18n.t('header.goodAfternoon!'));
    } else {
      setVolunteerGreeting(`${I18n.t('header.goodEvening')} ${name}!` || I18n.t('header.goodEvening!'));
    }
  };

  const count = async () => {
    getData('currentUser').then((user) => {
      calculateTime(user.firstname);
      setVolunteerDate(volunteerLength(user));
    });

    const idFormCount = await getData('offlineIDForms').then((idForms) => {
      if (idForms) {
        setOfflineForms(true);
        return idForms.length;
      }
      return 0;
    });

    const supplementaryCount = await getData('offlineSupForms').then((supForms) => {
      if (supForms) {
        setOfflineForms(true);
        return supForms.length;
      }
      return 0;
    });

    const assetIdFormCount = await getData('offlineAssetIDForms').then((assetIdForms) => {
      if (assetIdForms) {
        setOfflineForms(true);
        return assetIdForms.length;
      }
      return 0;
    });

    const assetSupForms = await getData('offlineAssetSupForms').then((assetSuppForms) => {
      if (assetSuppForms) {
        setOfflineForms(true);
        return assetSuppForms.length;
      }
      return 0;
    });

    const allFormOfflineCount = idFormCount + supplementaryCount + assetIdFormCount + assetSupForms;

    setOfflineFormCount(allFormOfflineCount);

    setOfflineForms(allFormOfflineCount > 0);

    setDrawerOpen(!drawerOpen);
  };

  const postOffline = async () => {
    const user = await getData('currentUser');

    const surveyUser = await surveyingUserFailsafe(user, undefined, isEmpty);
    const { organization } = user;
    const appVersion = await getData('appVersion') || '';
    const phoneOS = Platform.OS || '';

    const idFormsAsync = await getData('offlineIDForms');
    const supplementaryFormsAsync = await getData('offlineSupForms');
    const assetIdFormsAsync = await getData('offlineAssetIDForms');
    const assetSupFormsAsync = await getData('offlineAssetSupForms');
    const householdsAsync = await getData('offlineHouseholds');
    const householdRelationsAsync = await getData('offlineHouseholdsRelation');

    const offlineParams = {
      surveyData: idFormsAsync,
      supForms: supplementaryFormsAsync,
      households: householdsAsync,
      householdRelations: householdRelationsAsync,
      assetIdForms: assetIdFormsAsync,
      assetSupForms: assetSupFormsAsync,
      surveyingUser: surveyUser,
      surveyingOrganization: organization,
      parseUser: user.objectId,
      appVersion,
      phoneOS
    };
    checkOnlineStatus().then((connected) => {
      if (connected) {
        postOfflineForms(offlineParams).then(async (result) => {
          if (result) {
            await deleteData('offlineIDForms');
            await deleteData('offlineSupForms');
            await deleteData('offlineAssetIDForms');
            await deleteData('offlineAssetSupForms');
            await deleteData('offlineHouseholds');
            await deleteData('offlineHouseholdsRelation');
            setOfflineForms(false);
            setSubmission(true);
          } else {
            setSubmission(false);
          }
        }).catch((error) => {
          // handle session token error
          handleParseError(error, postOfflineForms).then(async (result) => {
            if (result) {
              await deleteData('offlineIDForms');
              await deleteData('offlineSupForms');
              await deleteData('offlineAssetIDForms');
              await deleteData('offlineAssetSupForms');
              await deleteData('offlineHouseholds');
              await deleteData('offlineHouseholdsRelation');
              setOfflineForms(false);
              setSubmission(true);
            } else {
              setSubmission(false);
            }
          }, () => {
            setSubmission(false);
          });
        });
      } else {
        setSubmission(false);
      }
    });
  };

  const cacheOfflineData = async () => {
    checkOnlineStatus().then(async (connected) => {
      if (connected) await populateResidentDataCache();
    });
  };

  const navToSettings = () => {
    setDrawerOpen(false);
    setSettings(true);
  };

  const navToCounts = () => {
    setShowCounts(true);
  };

  return (
    <View style={styles.container}>
      <View style={header}>
        <Text style={headerText}>{I18n.t('header.puente')}</Text>
        <View style={headerIcon}>
          <IconButton
            color={headerIcon.color}
            size={30}
          />
        </View>
        <View style={headerIcon}>
          <IconButton
            icon="tune"
            color={headerIcon.color}
            size={30}
            onPress={navToSettings}
          />
        </View>
      </View>
      {drawerOpen === true
        && (
          <View>
            {showCounts === false ? (
              <View>
                <Headline style={styles.calculationText}>
                  {volunteerGreeting}
                  <Emoji name="coffee" />
                </Headline>
                <View style={{ flexDirection: 'row', alignSelf: 'center' }}>
                  <Text style={styles.calculationText}>{`${I18n.t('header.volunteerSince')}\n${volunteerDate}`}</Text>
                </View>
                {offlineForms ? (
                  <Button onPress={postOffline}>
                    {I18n.t('header.submitOffline')}
                  </Button>
                ) : (
                  <Button disabled>{I18n.t('header.submitOffline')}</Button>
                )}
                {isOfflineLoading ? (
                  <Spinner color="blue" />
                ) : (
                  <Button onPress={cacheOfflineData}>{I18n.t('header.populateOffline')}</Button>
                )}
                {submission === false && (
                  <View>
                    <Text style={styles.calculationText}>{I18n.t('header.failedAttempt')}</Text>
                    <Text style={{ alignSelf: 'center' }}>{I18n.t('header.tryAgain')}</Text>
                    <Button onPress={() => setSubmission(null)}>{I18n.t('header.ok')}</Button>
                  </View>
                )}
                {submission === true && (
                  <View>
                    <Text style={styles.calculationText}>{I18n.t('header.success')}</Text>
                    <Text style={{ alignSelf: 'center' }}>
                      {I18n.t('header.justSubmitted')}
                      {' '}
                      {offlineFormCount}
                      {' '}
                      {offlineFormCount > 1 && (
                        <Text>{I18n.t('header.forms')}</Text>)}
                      {offlineFormCount === 1 && (
                        <Text>{I18n.t('header.form')}</Text>)}
                    </Text>
                    <Button onPress={() => setSubmission(null)}>{I18n.t('header.ok')}</Button>
                  </View>
                )}
                <View style={{ flexDirection: 'row' }}>
                  <Button
                    style={styles.calculationTextLeft}
                    onPress={navToSettings}
                  >
                    {I18n.t('header.settingsPage')}
                  </Button>
                  <Button
                    style={styles.calculationTextRight}
                    onPress={navToCounts}
                  >
                    {I18n.t('header.surveysCollected')}
                  </Button>
                </View>
              </View>
            ) : (
              <FormCounts
                setShowCounts={setShowCounts}
              />
            )}
          </View>
        )}
      <IconButton
        size={3}
        style={{
          width: 70, backgroundColor: 'grey', alignSelf: 'center', opacity: 0.5
        }}
        onPress={count}
      />

    </View>
  );
}
Example #7
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
Maps = ({ organization }) => {
  useEffect(() => {
    let isSubscribed = true;

    async function fetchRegion() {
      await getData('assetMapRegion').then((data) => {
        if (isSubscribed) {
          if (!data) {
            setRegion({
              latitude: 18.4861,
              longitude: -69.9312,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            });
          } else {
            setRegion(data);
          }
        }
      });
    }

    fetchRegion();

    return () => { isSubscribed = false; };
  }, []);

  const [region, setRegion] = useState();
  const [markers, setMarkers] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleLocation = async () => {
    setLoading(true);
    await getLocation().then((location) => {
      const { latitude, longitude } = location.coords;
      setRegion({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      });
      storeData({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      }, 'assetMapRegion');
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    });
    setLoading(false);
  };

  const retrieveMarkers = () => {
    setLoading(true);
    const queryParams = {
      skip: 0,
      offset: 0,
      limit: 10000,
      parseColumn: 'surveyingOrganization',
      parseParam: organization,
    };
    residentIDQuery(queryParams).then((records) => {
      const sanitizedRecords = JSON.parse(JSON.stringify(records));
      setMarkers(sanitizedRecords);
      setLoading(false);
    }).catch((e) => {
      setLoading(false);
      console.log(e); //eslint-disable-line
    });
  };

  // const retriveAsyncMarkers = () => {
  //   setLoading(true);
  //   getData('residentData').then((residentData) => {
  //     if (residentData) {
  //       setMarkers(residentData);
  //     }
  //     setLoading(false);
  //   });
  // };

  // const retrieveOnlineMarkers = () => {
  //   setLoading(true);
  // const queryParams = {
  //   skip: 0,
  //   offset: 0,
  //   limit: 10000,
  //   parseColumn: 'surveyingOrganization',
  //   parseParam: organization,
  // };

  //   residentIDQuery(queryParams).then((recs) => {
  //     const records = JSON.parse(JSON.stringify(recs));
  //     setMarkers(records);
  //     setLoading(false);
  //   });
  // };

  return (
    <View style={styles.container}>
      <MapView
        style={styles.mapStyle}
        region={region}
      >
        {markers && markers.map((marker) => (
          marker.location && (
            <Marker
              key={marker.objectId}
              coordinate={marker.location}
              title={`${marker.fname || ''} ${marker.lname || ''}`}
              description={`Collector: ${marker.surveyingUser}`}
            />
          )
        ))}
      </MapView>
      {loading
        && <Spinner style={styles.loading} color={theme.colors.primary} />}
      <View style={styles.buttonStyle}>
        <IconButton
          icon="crosshairs-gps"
          onPress={handleLocation}
          color={theme.colors.primary}
          style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
        />
        <IconButton
          icon="refresh"
          onPress={retrieveMarkers}
          color={theme.colors.primary}
          style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
        />
      </View>
    </View>
  );
}
Example #8
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
ResidentIdSearchbar = ({ surveyee, setSurveyee, surveyingOrganization }) => {
  const [query, setQuery] = useState('');
  const [residentsData, setResidentsData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [online, setOnline] = useState(true);
  const [searchTimeout, setSearchTimeout] = useState(null);
  const { residentOfflineData } = useContext(OfflineContext);

  useEffect(() => {
    checkOnlineStatus().then(async (connected) => {
      if (connected) fetchData(true, '');
      if (!connected) fetchData(false, '');
    });
  }, [surveyingOrganization]);

  const fetchOfflineData = async () => {
    setOnline(false);

    return residentOfflineData().then((residents) => {
      setResidentsData(residents);
      setLoading(false);
    });
  };

  const fetchOnlineData = async (qry) => {
    setOnline(true);

    const records = await parseSearch(surveyingOrganization, qry);

    let offlineData = [];

    await getData('offlineIDForms').then((offlineResidentData) => {
      if (offlineResidentData !== null) {
        Object.entries(offlineResidentData).forEach(([key, value]) => { //eslint-disable-line
          offlineData = offlineData.concat(value.localObject);
        });
      }
    });

    const allData = records.concat(offlineData);
    setResidentsData(allData.slice());
    setLoading(false);
  };

  const fetchData = (onLine, qry) => {
    if (!onLine) fetchOfflineData();
    if (onLine) fetchOnlineData(qry);
  };

  const filterOfflineList = () => residentsData.filter(
    (listItem) => {
      const fname = listItem.fname || ' ';
      const lname = listItem.lname || ' ';
      const nickname = listItem.nickname || ' ';
      return fname.toLowerCase().includes(query.toLowerCase())
        || lname
          .toLowerCase()
          .includes(query.toLowerCase())
        || `${fname} ${lname}`
          .toLowerCase()
          .includes(query.toLowerCase())
        || nickname
          .toLowerCase()
          .includes(query.toLowerCase());
    }
  );

  const onChangeSearch = (input) => {
    setLoading(true);

    if (input === '') setLoading(false);

    clearTimeout(searchTimeout);

    setQuery(input);

    setSearchTimeout(setTimeout(() => {
      fetchData(online, input);
    }, 1000));
  };

  const onSelectSurveyee = (listItem) => {
    setSurveyee(listItem);
    setQuery('');
  };

  const renderItem = ({ item }) => (
    <View>
      <Button onPress={() => onSelectSurveyee(item)} contentStyle={{ marginRight: 5 }}>
        <Text style={{ marginRight: 10 }}>{`${item?.fname || ''} ${item?.lname || ''}`}</Text>
        {/* offline IDform */}
        {item.objectId.includes('PatientID-') && (
          <View style={{
            backgroundColor: '#f8380e',
            width: 1,
            height: 10,
            paddingLeft: 10,
            marginTop: 'auto',
            marginBottom: 'auto',
            borderRadius: 20
          }}
          />
        )}
      </Button>
    </View>
  );

  return (
    <View>
      <Headline style={styles.header}>{I18n.t('residentIdSearchbar.searchIndividual')}</Headline>
      <Searchbar
        placeholder={I18n.t('findResident.typeHere')}
        onChangeText={onChangeSearch}
        value={query}
      />
      {!online
        && <Button onPress={() => fetchData(false, '')}>{I18n.t('global.refresh')}</Button>}
      {loading
        && <Spinner color="blue" />}

      {query !== '' && (
        <FlatList
          data={online ? residentsData : filterOfflineList(residentsData)}
          renderItem={renderItem}
          keyExtractor={(item) => item.objectId}
        />
      )}

      {surveyee && surveyee.objectId && (
        <ResidentCard resident={surveyee} />
      )}
    </View>
  );
}
Example #9
Source File: index.js    From puente-reactnative-collect with MIT License 4 votes vote down vote up
ViewAssets = ({ organization, switchAssetPage }) => {
  useEffect(() => {
    let isSubscribed = true;

    async function fetchRegion() {
      await getData('assetMapRegion').then((data) => {
        if (isSubscribed) {
          if (!data) {
            setRegion({
              latitude: 18.4861,
              longitude: -69.9312,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            });
          } else {
            setRegion(data);
          }
        }
      });
    }

    fetchRegion();

    return () => { isSubscribed = false; };
  }, []);

  const [region, setRegion] = useState();
  const [markers, setMarkers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedMarker, setSelectedMarker] = useState();

  const handleLocation = async () => {
    setLoading(true);
    await getLocation().then((location) => {
      const { latitude, longitude } = location.coords;
      setRegion({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      });
      storeData({
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        latitude,
        longitude,
      }, 'assetMapRegion');
    }).catch((e) => {
      console.log(e) //eslint-disable-line
    });
    setLoading(false);
  };

  const retrieveMarkers = () => {
    setLoading(true);
    assetDataQuery(organization).then((records) => {
      const sanitizedRecords = JSON.parse(JSON.stringify(records));
      setMarkers(sanitizedRecords);
      setLoading(false);
    }).catch((e) => {
      setLoading(false);
      console.log(e); //eslint-disable-line
    });
  };

  return (
    <View>
      <View style={styles.container}>
        <MapView
          style={styles.mapStyle}
          region={region}
        >
          {markers && markers.map((marker) => (
            marker.location && (
              <Marker
                key={marker.objectId}
                coordinate={marker.location}
                title={`${marker.name || ''}`}
                // description={`Collector: ${marker.surveyingOr}`}
                onPress={() => setSelectedMarker(marker)}
              />
            )
          ))}

        </MapView>
        <View style={styles.buttonStyle}>
          <IconButton
            icon="crosshairs-gps"
            onPress={handleLocation}
            color={theme.colors.primary}
            style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
          />
          <IconButton
            icon="refresh"
            onPress={retrieveMarkers}
            color={theme.colors.primary}
            style={{ backgroundColor: theme.colors.background, opacity: 0.8 }}
          />
        </View>
        {loading
          && <Spinner style={styles.loading} color={theme.colors.primary} />}

      </View>
      <View style={styles.container}>
        {selectedMarker
          && (
            <SelectedAsset
              selectedMarker={selectedMarker}
              style={{ position: 'absolute' }}
              switchAssetPage={switchAssetPage}
            />
          )}
      </View>
    </View>
  );
}