Snippets Collections

1. Distance-based Pricing
A food delivery service charges a base fee of $2, plus $1.50 per mile for delivery. If the customer is 5 miles away, the fare will be:

Base Fare = $2
Distance Fare = $1.50 × 5 = $7.50
Total Fare = $2 + $7.50 = $9.50

2. Time-based Pricing
A grocery delivery service charges based on time taken. There’s a base fee of $3, plus $0.10 per minute for the duration of the delivery. If a delivery takes 45 minutes:

Base Fare = $3
Time Fare = $0.10 × 45 = $4.50
Total Fare = $3 + $4.50 = $7.50

3. Weight/Size-based Pricing
A furniture delivery service charges a base fee of $10, plus $2 per 10 lbs for items over 50 lbs. If a delivered item weighs 70 lbs:

Base Fare = $10
Weight Fare = $2 × 2 = $4
Total Fare = $10 + $4 = $14

4. Dynamic/Surge Pricing
A ride-sharing delivery charges a base fare of $5, with $2 per mile, but due to high demand, a surge multiplier of 1.5x is applied. For a 4-mile delivery:

Base Fare = $5
Distance Fare = $2 × 4 = $8
Surge Multiplier = 1.5
Total Fare = ($5 + $8) × 1.5 = $19.50

5. Zonal Pricing
A local courier service charges $10 for deliveries within Zone A and $15 for Zone B. If a delivery is in Zone B:

Zone Fare = $15
Total Fare = $15

6. Hybrid Pricing (Distance + Time)
A parcel delivery service charges a base fare of $3, $1 per mile, and $0.05 per minute. If a 10-mile delivery takes 30 minutes:

Base Fare = $3
Distance Fare = $1 × 10 = $10
Time Fare = $0.05 × 30 = $1.50
Total Fare = $3 + $10 + $1.50 = $14.50

7. Fuel Surcharge Additions
A delivery service charges $2 per mile, but also adds a $0.10 per mile fuel surcharge when fuel prices rise. For a 12-mile delivery:

Base Fare = $2 × 12 = $24
Fuel Surcharge = $0.10 × 12 = $1.20
Total Fare = $24 + $1.20 = $25.20

8. Crowdsourced/Bid-based Pricing
In a freelance courier platform, drivers bid for deliveries. A customer needs to deliver a package 5 miles away. Three drivers submit bids:

Driver 1: $15
Driver 2: $12
Driver 3: $18
The customer selects Driver 2’s bid of $12.
//Regular 
import React, { useState, useEffect } from 'react';
import { View, FlatList, ListItem, Button, Avatar } from 'react-native';
import firestore from '@react-native-firebase/firestore';

// Assuming filteredData is your initial data source
const YourComponent = () => {
  const [visibleData, setVisibleData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [lastVisible, setLastVisible] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setIsLoading(true);
    try {
      const querySnapshot = await firestore()
        .collection('your_collection')
        .orderBy('createdAt', 'desc')
        .limit(10)
        .get();

      const newData = querySnapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      
      setVisibleData(newData);
      setLastVisible(querySnapshot.docs[querySnapshot.docs.length - 1]);
    } catch (error) {
      console.error('Error fetching data: ', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchMoreData = async () => {
    setIsLoading(true);
    try {
      const querySnapshot = await firestore()
        .collection('your_collection')
        .orderBy('createdAt', 'desc')
        .startAfter(lastVisible)
        .limit(10)
        .get();

      const newData = querySnapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      
      setVisibleData((prevData) => [...prevData, ...newData]);
      setLastVisible(querySnapshot.docs[querySnapshot.docs.length - 1]);
    } catch (error) {
      console.error('Error fetching more data: ', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleEndReached = () => {
    if (!isLoading) {
      fetchMoreData();
    }
  };

  return (
    <FlatList
      data={visibleData}
      keyExtractor={(item) => item.id}
      ListEmptyComponent={() =>
        isLoading ? <EventMenuProduct /> : <NoData />
      }
      onEndReached={handleEndReached}
      onEndReachedThreshold={0.1} // Adjust this threshold as needed
      renderItem={({ item, index }) => (
        <View
          key={index}
          style={{
            alignContent: 'center',
            alignSelf: 'center',
          }}
        >
          {/* Your existing renderItem logic */}
        </View>
      )}
    />
  );
};

export default YourComponent;


/// With my code
import React, { useState, useEffect } from 'react';
import { View, FlatList, ListItem, Button, Avatar } from 'react-native';
import { collection, getDocs, onSnapshot } from 'firebase/firestore';
import { db } from 'your-firebase-config-file'; // Import your Firebase database config

// Assuming filteredData is your initial data source
const YourComponent = ({ category }) => {
  const [products, setProducts] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [lastDoc, setLastDoc] = useState(null);

  useEffect(() => {
    fetchMenuData();
  }, []);

  const fetchMenuData = async () => {
    setIsLoading(true);
    try {
      const subCollectionNames = getCategorySubCollectionNames(category);

      const allProducts = [];

      const subCollectionPromises = subCollectionNames.map(async (subCollectionName) => {
        const subCollectionRef = collection(db, `vehicles/${category}/${subCollectionName}`);
        const subCollectionSnapshot = await getDocs(subCollectionRef);

        subCollectionSnapshot.forEach((doc) => {
          allProducts.push({ id: doc.id, ...doc.data() });
        });

        const unsubscribe = onSnapshot(subCollectionRef, (snapshot) => {
          snapshot.docChanges().forEach((change) => {
            if (change.type === 'added') {
              setProducts((prevProducts) => [...prevProducts, { id: change.doc.id, ...change.doc.data() }]);
            }
          });
        });

        return () => unsubscribe();
      });

      await Promise.all(subCollectionPromises);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching menu data:', error);
      setIsLoading(false);
    }
  };

  const getCategorySubCollectionNames = (category) => {
    switch (category) {
      case 'Buying':
        return ['subCollectionName1', 'subCollectionName2']; // Adjust with your subcollection names
      case 'Renting':
        return ['subCollectionName3', 'subCollectionName4']; // Adjust with your subcollection names
      default:
        return [];
    }
  };

  const handleEndReached = () => {
    if (!isLoading) {
      fetchMoreData();
    }
  };

  const fetchMoreData = async () => {
    setIsLoading(true);
    try {
      const subCollectionNames = getCategorySubCollectionNames(category);

      const allProducts = [];

      const subCollectionPromises = subCollectionNames.map(async (subCollectionName) => {
        const subCollectionRef = collection(db, `vehicles/${category}/${subCollectionName}`);

        const query = lastDoc ? subCollectionRef.startAfter(lastDoc) : subCollectionRef;

        const subCollectionSnapshot = await getDocs(query);

        subCollectionSnapshot.forEach((doc) => {
          allProducts.push({ id: doc.id, ...doc.data() });
        });

        const lastDocument = subCollectionSnapshot.docs[subCollectionSnapshot.docs.length - 1];
        setLastDoc(lastDocument);

        return allProducts;
      });

      const productsArray = await Promise.all(subCollectionPromises);
      const mergedProducts = productsArray.reduce((acc, curr) => acc.concat(curr), []);

      setProducts((prevProducts) => [...prevProducts, ...mergedProducts]);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching more data:', error);
      setIsLoading(false);
    }
  };

  return (
    <FlatList
      data={products}
      keyExtractor={(item) => item.id}
      ListEmptyComponent={() => isLoading ? <EventMenuProduct /> : <NoData />}
      onEndReached={handleEndReached}
      onEndReachedThreshold={0.1}
      renderItem={({ item }) => (
        <View style={{ /* Your styling */ }}>
          {/* Your rendering logic */}
        </View>
      )}
    />
  );
};

export default YourComponent;

import React, { useState, useEffect } from 'react';
import { View, FlatList, ListItem, Button, Avatar } from 'react-native';
import firestore from '@react-native-firebase/firestore';

// Assuming filteredData is your initial data source
const YourComponent = () => {
  const [visibleData, setVisibleData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [lastVisible, setLastVisible] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setIsLoading(true);
    try {
      const querySnapshot = await firestore()
        .collection('your_collection')
        .orderBy('createdAt', 'desc')
        .limit(10)
        .get();

      const newData = querySnapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      
      setVisibleData(newData);
      setLastVisible(querySnapshot.docs[querySnapshot.docs.length - 1]);
    } catch (error) {
      console.error('Error fetching data: ', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchMoreData = async () => {
    setIsLoading(true);
    try {
      const querySnapshot = await firestore()
        .collection('your_collection')
        .orderBy('createdAt', 'desc')
        .startAfter(lastVisible)
        .limit(10)
        .get();

      const newData = querySnapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      
      setVisibleData((prevData) => [...prevData, ...newData]);
      setLastVisible(querySnapshot.docs[querySnapshot.docs.length - 1]);
    } catch (error) {
      console.error('Error fetching more data: ', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleEndReached = () => {
    if (!isLoading) {
      fetchMoreData();
    }
  };

  return (
    <FlatList
      data={visibleData}
      keyExtractor={(item) => item.id}
      ListEmptyComponent={() =>
        isLoading ? <EventMenuProduct /> : <NoData />
      }
      onEndReached={handleEndReached}
      onEndReachedThreshold={0.1} // Adjust this threshold as needed
      renderItem={({ item, index }) => (
        <View
          key={index}
          style={{
            alignContent: 'center',
            alignSelf: 'center',
          }}
        >
          {/* Your existing renderItem logic */}
        </View>
      )}
    />
  );
};

export default YourComponent;
star

Wed Nov 06 2024 17:31:55 GMT+0000 (Coordinated Universal Time)

#eventelysium

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension