types#Party TypeScript Examples

The following examples show how to use types#Party. 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: Share.test.tsx    From lets-fork-native with MIT License 5 votes vote down vote up
party: Party = { id: '123456', status: 'waiting' }
Example #2
Source File: hooks.ts    From lets-fork-native with MIT License 5 votes vote down vote up
usePrevious = (value: Party): React.MutableRefObject<Party>['current'] => {
  const ref = React.useRef({} as Party)
  React.useEffect(() => {
    ref.current = value
  })
  return ref.current
}
Example #3
Source File: App.tsx    From lets-fork-native with MIT License 4 votes vote down vote up
export default function App(): React.ReactElement {
  const [showApp, setShowApp] = React.useState(false)
  const [fontsLoaded] = useFonts({ VarelaRound_400Regular })
  const [loading, setLoading] = React.useState<boolean>(true)
  const [location, setLocation] = React.useState<Location.LocationObject>()
  const [party, setParty] = React.useState<Party>({} as Party)

  const linking = {
    prefixes: ['https://letsfork.app', 'letsfork://', 'exp://192.168.178.76:19000/+'],
    config: {
      screens: {
        Party: 'party/:id',
      },
    },
  }

  React.useEffect(() => {
    // Keep track of current matches
    let matches: Restaurant[] = []

    ws.onopen = (): void => {
      console.log('opened')
    }

    ws.onmessage = (msg): void => {
      console.log(msg.data)
      const data: Party = JSON.parse(msg.data)

      const newMatches = JSON.stringify(data.matches?.map((r) => r.id).sort())
      const oldMatches = JSON.stringify(matches?.map((r) => r.id).sort())

      // Alert when there are new matches
      if (data.matches?.length
        && oldMatches !== newMatches) {
        matches = data.matches
        Alert.alert(
          'You have a new match!',
          'Click the icon in the top right to view your matches',
        )
      }

      setParty(data)
    }

    ws.onclose = (msg): void => {
      console.log('closed', msg.reason)
    }

    ws.onerror = (err): void => {
      console.log('websocket error:', err)
    }
  }, [])

  const loadApplicationAsync = async (): Promise<void> => {
    const { status } = await Location.requestPermissionsAsync()
    if (status !== 'granted') {
      console.log('Permission to access location was denied')
    }

    const [loc, val] = await Promise.all([
      Location.getCurrentPositionAsync({}),
      AsyncStorage.getItem('showApp'),
    ])

    if (loc) setLocation(loc)

    // User has seen intro
    if (val) setShowApp(true)
  }

  if (loading || !fontsLoaded) {
    return (
      <AppLoading
        startAsync={loadApplicationAsync}
        onFinish={(): void => setLoading(false)}
        onError={console.warn}
      />
    )
  }

  if (!showApp) {
    return <TutorialScreen setShowApp={setShowApp} />
  }

  return (
    <NavigationContainer linking={linking} fallback={<Text>Loading...</Text>}>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen
          name="Create"
          options={(): object => ({
            headerTitle: (): null => null,
          })}
        >
          {(props): React.ReactElement => (
            <CreateScreen
              {...props}
              ws={ws}
              location={location}
            />
          )}
        </Stack.Screen>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={(): object => ({
            headerShown: false,
          })}
        />
        <Stack.Screen
          name="Join"
          options={(): object => ({
            headerTitle: (): null => null,
          })}
        >
          {(props): React.ReactElement => <JoinScreen {...props} ws={ws} />}
        </Stack.Screen>
        <Stack.Screen
          name="Match"
          options={(): object => ({
            headerTitle: (): null => null,
          })}
        >
          {(props): React.ReactElement => <MatchScreen {...props} party={party} />}
        </Stack.Screen>
        <Stack.Screen
          name="Party"
          options={({ navigation }): object => ({
            gestureEnabled: false,
            headerTitle: (): null => null,
            headerLeft: (): React.ReactElement => (
              <TouchableOpacity
                style={styles.backButton}
                onPress={(): void => Alert.alert(
                  'Are you sure you want to exit?',
                  'Exiting will make you lose all data in this party',
                  [
                    { text: 'Cancel' },
                    {
                      text: 'OK',
                      onPress: (): void => {
                        ws.send(JSON.stringify({ type: 'quit' }))
                        navigation.navigate('Home')
                        setParty({} as Party)
                      },
                    },
                  ],
                  { cancelable: true },
                )}
              >
                <MaterialIcons name="close" color="black" size={24} />
              </TouchableOpacity>
            ),
            headerRight: (): React.ReactElement | null => (
              party.status === 'active'
                ? <Menu navigation={navigation} />
                : null
            ),
          })}
        >
          {(props): React.ReactElement => (
            <PartyScreen
              {...props}
              ws={ws}
              party={party}
              setParty={setParty}
            />
          )}
        </Stack.Screen>
        <Stack.Screen
          name="Restaurant"
          component={RestaurantScreen}
          options={(): object => ({
            headerTitle: (): null => null,
          })}
        />
        <Stack.Screen
          name="Share"
          options={(): object => ({
            headerTitle: (): null => null,
          })}
        >
          {(props): React.ReactElement => (
            <ShareScreen {...props} party={party} />
          )}
        </Stack.Screen>
      </Stack.Navigator>
    </NavigationContainer>
  )
}
Example #4
Source File: PartyScreen.tsx    From lets-fork-native with MIT License 4 votes vote down vote up
PartyScreen = React.memo((props: Props) => {
  const {
    navigation, party, route, setParty, ws,
  } = props

  const [snapIndex, setSnapIndex] = React.useState(2)
  const [finished, setFinished] = React.useState<boolean>(false)
  const [restaurants, setRestaurants] = React.useState<Restaurant[]>()
  const headerHeight = useHeaderHeight()
  const viewHeight = env.ADS ? height - headerHeight - 50 : height - headerHeight

  if (party?.error) {
    Alert.alert(
      'Yike! Something went wrong',
      party.error,
      [
        {
          text: 'OK',
          onPress: (): void => {
            navigation.navigate('Home')
            setParty({} as Party)
          },
        },
      ],
      { cancelable: false },
    )
  }

  // Request more cards with 3 remaining to prevent
  // having to show loader
  React.useEffect(() => {
    if (restaurants && restaurants?.length === 3) {
      ws.send(JSON.stringify({ type: 'request-more' }))
    }
  }, [restaurants, restaurants?.length, ws])

  // Deep linking will open the app to the party screen
  // but the party still needs to be joined
  React.useEffect(() => {
    if (route?.params?.id) {
      ws.send(JSON.stringify({ type: 'join', payload: { party_id: route?.params?.id } }))
    }
  }, [route?.params?.id, ws])

  // When anyone requests more cards, they are set in current
  // and this useEffect loads the new cards into the restaurants array
  const prevState = usePrevious(party || {} as Party)
  React.useEffect(() => {
    if (JSON.stringify(prevState.current) !== JSON.stringify(party?.current)) {
      if (party?.current?.length && restaurants) {
        const res = [...restaurants, ...party?.current]
        setRestaurants(res)
      }
    }
  }, [party, prevState, restaurants])

  // Custom android back button
  useFocusEffect( // eslint-disable-line
    React.useCallback(() => {
      const onBackPress = (): boolean => {
        Alert.alert(
          'Are you sure you want to exit?',
          'Exiting will make you lose all data in this party',
          [
            { text: 'Cancel' },
            {
              text: 'OK',
              onPress: (): void => {
                ws.send(JSON.stringify({ type: 'quit' }))
                navigation.navigate('Home')
                setParty({} as Party)
              },
            },
          ],
          { cancelable: true },
        )
        return true
      }

      BackHandler.addEventListener('hardwareBackPress', onBackPress)

      return (): void => BackHandler.removeEventListener('hardwareBackPress', onBackPress)
    }, [navigation, setParty, ws]),
  )

  const handleSwipeRight = (id: string): void => {
    ws.send(JSON.stringify({ type: 'swipe-right', payload: { restaurant_id: id } }))
  }

  if (party?.status === 'waiting') {
    return <Share party={party} ws={ws} />
  }

  if (finished || party?.total === 0) {
    return (
      <View
        style={{
          ...styles.waiting,
          height: viewHeight,
        }}
      >
        <Text style={styles.text}>
          No more restaurants.
          Go through the list again or try expanding your search range.
        </Text>
        <Button
          size="sm"
          color="purple"
          onPress={(): void => {
            setFinished(false)
            setRestaurants(party?.restaurants)
          }}
        >
          START OVER
        </Button>
      </View>
    )
  }

  if (!party || !party.restaurants) {
    return (
      <View
        style={{
          ...styles.waiting,
          height: viewHeight,
        }}
      >
        <ActivityIndicator size="large" />
      </View>
    )
  }

  const current = restaurants?.length
    ? restaurants[0] : party.restaurants[0]

  return (
    <SafeAreaView style={styles.container}>
      <View
        // disable swiping while BottomSheet is open
        pointerEvents={snapIndex !== 2 ? 'none' : 'auto'}
        style={{ height: viewHeight, zIndex: 0 }}
      >
        <SwipeWindow
          handleSwipeRight={handleSwipeRight}
          restaurants={restaurants || party.restaurants}
          setFinished={setFinished}
          setRestaurants={setRestaurants}
        />
      </View>
      <ScrollBottomSheet
        componentType="ScrollView"
        contentContainerStyle={styles.scrollBottomSheet}
        snapPoints={[100, 100, viewHeight - BOTTOM_BAR_HEIGHT]}
        initialSnapIndex={2}
        onSettle={setSnapIndex}
        renderHandle={(): React.ReactElement => <Handle />}
        animationConfig={{
          duration: 100,
        }}
      >
        <Details restaurant={current} />
      </ScrollBottomSheet>
    </SafeAreaView>
  )
})