react-native-paper#Searchbar JavaScript Examples

The following examples show how to use react-native-paper#Searchbar. 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: Menu.js    From salyd with GNU General Public License v3.0 4 votes vote down vote up
Menu = (props) => {
    const { token, globalRoomId, globalTableId, updateOrder, order, localroomId, restro } = useContext(
        GlobalContext
    );
    const [menu, setMenu] = useState([]);
    const [permission, setPermission] = useState("");
    const [user, setUser] = useState({});
    const [search, setSearch] = useState("");
    const [data_temp, setdata_temp] = useState([]);

    useEffect(() => {
        const getPermission = async () => {
            const userId = await AsyncStorage.getItem("userId");

            console.log(token, "token from Menu.js");
            //Fetching permission role for logged in user using token
            if (token) {
                fetch(`${apiUrl}/permission/get`, {
                    headers: {
                        Authorization: "Bearer " + token,
                    },
                })
                    .then((res) => res.json())
                    .then((data) => {
                        //Setting user details
                        setUser(data.user);

                        //Setting user permission
                        console.log(data.user.role, "logged in user");
                        setPermission(data.user.role);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }

            //Fetching permission role for guest user using userId
            else if (userId) {
                fetch(`${apiUrl}/permission/get`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        id: userId,
                    }),
                })
                    .then((res) => res.json())
                    .then((data) => {
                        //Setting user details
                        setUser(data.user);
                        console.log(data.user.role, "guest user");

                        //Setting user permissions
                        setPermission(data.user.role);
                    });
            }
        };

        const getMenu = async () => {
            const roomId = globalRoomId;

            console.log(roomId, "roomId");

            //Fetching menu for logged in user
            if (token) {
                fetch(`${apiUrl}/menu`, {
                    headers: {
                        Authorization: "Bearer " + token,
                    },
                })
                    .then((res) => res.json())
                    .then((data) => {
                        //Providing the rooms with unique id

                        socket.emit("joinRoom", user.name, globalTableId);

                        //Initializing the counter
                        data.tableOf.menu.map((elem) => {
                            elem.count = 0;
                        });

                        //Setting the menu
                        setMenu(data.tableOf.menu);
                        setdata_temp(data.tableOf.menu);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }

            //Fetching menu for guest user using roomId stored in async storage
            else if (roomId) {
                fetch(`${apiUrl}/menu/guest`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        roomId: roomId,
                    }),
                })
                    .then((res) => res.json())
                    .then((data) => {
                        //Providing the rooms with unique id
                        socket.emit("joinRoom", user.name, globalTableId);
                        //Initializing the counter
                        data.tableOf.menu.map((elem) => {
                            elem.count = 0;
                        });

                        //Setting the menu
                        setMenu(data.tableOf.menu);
                        setdata_temp(data.tableOf.menu);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            }
        };

        getPermission();
        getMenu();
    }, []);

    console.log(restro, "restro global state")
    //Emitting the joinRoom event to the server
    //Event emitted @Server

    //Increasing the no of items
    const incrementCounter = (id, index) => {
        if (id === menu[index]._id) {
            let newMenu = [...menu];
            newMenu[index].count += 1;
            setMenu(newMenu);

            //Emitting the counter(increment) change event @Sever
            socket.emit("countChange", menu, globalTableId);
        }
    };

    //Decreasing the no of items
    const decrementCounter = (id, index) => {
        if (id === menu[index]._id) {
            let newMenu = [...menu];
            if (newMenu[index].count > 0) {
                newMenu[index].count -= 1;
            } else {
                newMenu[index].count = 0;
            }
            setMenu(newMenu);

            //Emitting the counter(decrement) change event @Sever
            socket.emit("countChange", menu, globalTableId);
        }
    };

    //Placing order
    const orderPlaced = () => {
        updateOrder({
            orderId: globalTableId,
            menu
        })
        props.navigation.push("Checkout");
        // socket.emit('orderPlaced',"Hi");
    };

    //Listening for the menuChange event from @Sever

    socket.on("menuChange", (menu) => {
        setMenu(menu);
    });

    const renderList = (item, index) => (
        <View style={styles.item}>
            <View style={styles.content}>
                <Text style={styles.name}>{item.item}</Text>
                <Text style={styles.desc}>Lorem ipsum, quos</Text>

                <View style={styles.price}>
                    <Text style={styles.textPrice}>₹ {item.price}</Text>
                </View>
            </View>
            <View style={styles.counterContainer}>
                <TouchableOpacity
                    onPress={() => decrementCounter(item._id, index)}
                    disabled={permission === "view" ? true : false}
                >
                    <View style={styles.counter}>
                        <Text style={styles.textCounter}>-</Text>
                    </View>
                </TouchableOpacity>

                <Text style={styles.main_count}> {menu[index].count} </Text>

                <TouchableOpacity
                    onPress={() => incrementCounter(item._id, index)}
                    disabled={permission === "view" ? true : false}
                >
                    <View style={styles.counter}>
                        <Text style={styles.textCounter}>+</Text>
                    </View>
                </TouchableOpacity>
            </View>
        </View>
    );

    const _search = (text) => {
        let data = [];
        data_temp.map(function (value) {
            if (value.item.indexOf(text) > -1) {
                data.push(value);
            }
        });

        setMenu(data);
        setSearch(text);
    };

    const ItemSeparatorComponent = () => {
        return (
            <View
                style={{
                    height: 10,
                }}
            />
        );
    };

    return (
        <View style={styles.container}>
            <Header navigation={props.navigation}>Menu</Header>

            <Searchbar
                style={{
                    margin: 15,
                    borderRadius: 40,
                }}
                placeholder="Search"
                onChangeText={_search}
                value={search}
            />

            <View style={styles.flatList}>
                <FlatList
                    data={menu}
                    renderItem={({ item, index }) => {
                        return renderList(item, index);
                    }}
                    keyExtractor={(item) => item._id}
                    ItemSeparatorComponent={() => ItemSeparatorComponent()}
                    showsVerticalScrollIndicator={true}
                ></FlatList>
            </View>

            {permission === "admin" ? (
                <View style={{
                    justifyContent: "center",
                    alignItems: "center",
                    marginBottom: 20
                }}>
                    <Button
                        onPressFunction={() => orderPlaced()}
                    >Give order</Button>
                </View>
            ) : null}
        </View>
    );
}
Example #2
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 #3
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 #4
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>
  );
}