aws-amplify#graphqlOperation TypeScript Examples

The following examples show how to use aws-amplify#graphqlOperation. 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: UserHabits.tsx    From nyxo-website with MIT License 6 votes vote down vote up
getHabits = async (): Promise<Array<Habit | null> | null | undefined> => {
  try {
    const response = (await API.graphql(graphqlOperation(listHabits, {}))) as {
      data: ListHabitsQuery
    }
    return response.data.listHabits?.items
  } catch (error) {
    console.warn(error)
    return undefined
  }
}
Example #2
Source File: Sensors.tsx    From aws-appsync-iot-core-realtime-dashboard with MIT No Attribution 6 votes vote down vote up
GetSensors = async (): Promise<Array<ISensor>> => {

    try {

        const response = (await API.graphql(graphqlOperation(listSensors))) as {
            data: ListSensorsQuery;
        };

        if (response.data && response.data.listSensors) {
            
            const r = response.data.listSensors as Array<ISensor>;
            
            return r;
        }
        else {

            return Array<ISensor>();
        }

    } catch (error) {
        throw error;
    }
}
Example #3
Source File: coaching.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
getCoaching = async (
  _key: string,
  { id }: { id: string }
): Promise<GetCoachingDataQuery['getCoachingData']> => {
  try {
    const {
      data: { getCoachingData: data }
    } = (await API.graphql(graphqlOperation(getCoachingData, { id }))) as {
      data: GetCoachingDataQuery
    }

    return data
  } catch (error) {
    return error
  }
}
Example #4
Source File: bookmark-hooks.tsx    From nyxo-website with MIT License 6 votes vote down vote up
fetchAllBookmarks = async () => {
  try {
    const {
      data: { listLikedContents: result = { items: [] } },
    } = (await API.graphql(graphqlOperation(listLikedContents))) as {
      data: ListLikedContentsQuery
    }

    if (!result || !result.items) return []

    return result.items
  } catch (error) {
    return error
  }
}
Example #5
Source File: todo.service.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
async CreateTodo(input: CreateTodoMutationVariables): Promise<CreateTodoMutation> {
    const statement = `mutation CreateTodo($input: CreateTodoInput!) {
        createTodo(input: $input) {
          id
          name
          description
        }
      }`;
    const response = await this.amplifyService.api().graphql(graphqlOperation(statement, input));
    return <CreateTodoMutation>response.data;
  }
Example #6
Source File: index.tsx    From TwitterClone with MIT License 6 votes vote down vote up
UserFleetsList = () => {

  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await API.graphql(graphqlOperation(listUsers));
        setUsers(data.data.listUsers.items);
      } catch (e) {
        console.log(e)
      }
    }
    fetchData();
  }, [])

  return (
    <View>
      <FlatList
        data={users}
        renderItem={({item}) => <UserFleetPreview user={item} />}
        horizontal
        showsHorizontalScrollIndicator={false}
      />
    </View>
  )
}
Example #7
Source File: HomeScreen.tsx    From SpotifyClone with MIT License 6 votes vote down vote up
export default function HomeScreen() {

  const [categories, setCategories] = useState([]);

  useEffect(() => {
    const fetchAlbumCategories = async () => {
      try {
        const data = await API.graphql(graphqlOperation(listAlbumCategorys));
        setCategories(data.data.listAlbumCategorys.items);
      } catch (e) {
        console.log(e);
      }
    }

    fetchAlbumCategories();
  }, []);


  return (
    <View style={styles.container}>
       <FlatList
         data={categories}
         renderItem={({ item }) => (
           <AlbumCategory
             title={item.title}
             albums={item.albums.items}
           />
         )}
         keyExtractor={(item) => item.id}
       />
    </View>
  );
}
Example #8
Source File: todo.service.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
async GetTodo(input: GetTodoQueryVariables): Promise<GetTodoQuery> {
    const statement = `query GetTodo($id: ID!) {
        getTodo(id: $id) {
          id
          name
          description
        }
      }`;
    const response = await this.amplifyService.api().graphql(graphqlOperation(statement, input));
    return <GetTodoQuery>response.data;
  }
Example #9
Source File: AlbumScreen.tsx    From SpotifyClone with MIT License 6 votes vote down vote up
AlbumScreen = () => {

  const route = useRoute();
  const albumId = route.params.id;

  const [album, setAlbum] = useState(null)

  useEffect(() => {
    const fetchAlbumDetails = async () => {
      try {
        const data = await API.graphql(graphqlOperation(getAlbum, { id: albumId }))
        setAlbum(data.data.getAlbum)
      } catch (e) {
        console.log(e);
      }
    }

    fetchAlbumDetails();
  }, [])

  if (!album) {
    return <Text>Loading...</Text>
  }

  return (
    <View>
      <FlatList
        data={album.songs.items}
        renderItem={({ item }) => <SongListItem song={item} />}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={() => <AlbumHeader album={album} />}
      />
    </View>
  )
}
Example #10
Source File: Sensors.tsx    From aws-appsync-iot-core-realtime-dashboard with MIT No Attribution 6 votes vote down vote up
GetSensor = async (sensorId: string): Promise<ISensor | null> => {

    try {

        const response = (await API.graphql(graphqlOperation(getSensor, {sensorId: sensorId}))) as {
            data: GetSensorQuery;
        };

        if (response.data.getSensor){
            
            const r = response.data.getSensor as ISensor;
            
            return r;
        }
        else {

            return null;
        }

    } catch (error) {
        throw error;
    }
}
Example #11
Source File: todo.service.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
OnDeleteTodoListener: Observable<OnDeleteTodoSubscription> = this.amplifyService.api().graphql(
    graphqlOperation(
      `subscription OnDeleteTodo {
        onDeleteTodo {
          id
          name
          description
        }
      }`
    )
  ) as Observable<OnDeleteTodoSubscription>;
Example #12
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
App = () => {
  const [formState, setFormState] = useState(initialState);
  const [todos, setTodos] = useState([]);

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

  const setInput = (key: any, value: any):any => {
    setFormState({ ...formState, [key]: value });
  }

  const fetchTodos = async (): Promise<any> => {
    try {
      const todoData:any = await API.graphql(graphqlOperation(listTodos));
      const todos:any = todoData.data.listTodos.items;
      setTodos(todos);
    } catch (err) { 
      console.log('error fetching todos');
    }
  }

  const addTodo = async (): Promise<any> => {
    try {
      if (!formState.name || !formState.description) return;
      const todo = { ...formState };
      setTodos([...todos, todo] as SetStateAction<never[]>);
      setFormState(initialState);
      await API.graphql(graphqlOperation(createTodo, {input: todo}));
    } catch (err) {
      console.log('error creating todo:', err);
    }
  }

  return (
    <div className="container">
      <h2>Amplify Todos</h2>
      <input
        onChange={event => setInput('name', event.target.value)}
        value={formState.name} 
        placeholder="Name"
      />
      <input
        onChange={event => setInput('description', event.target.value)}
        value={formState.description}
        placeholder="Description"
      />
      <button onClick={addTodo}>Create Todo</button>
      {
        todos.map((todo: any, index: any) => (
          <div key={todo.id ? todo.id : index} className="todo">
            <p className="todoName">{todo.name}</p>
            <p className="todoDescription">{todo.description}</p>
          </div>
        ))
      }
    </div>
  )
}
Example #13
Source File: bookmark-hooks.tsx    From nyxo-website with MIT License 5 votes vote down vote up
fetchHabitBookmarks = async () => {
  return (await API.graphql(
    graphqlOperation(listLikedContents, { filter: { type: { eq: "habit" } } })
  )) as { data: ListLikedContentsQuery }
}
Example #14
Source File: App.tsx    From TwitterClone with MIT License 5 votes vote down vote up
function App() {
  const isLoadingComplete = useCachedResources();
  const colorScheme = useColorScheme();

  const getRandomImage = () => {
    return 'https://scontent.fkiv3-1.fna.fbcdn.net/v/t31.0-8/s960x960/22256588_1932617800312085_5686197942193420542_o.jpg?_nc_cat=110&_nc_sid=85a577&_nc_ohc=svjjE7DUkc0AX9yjcdC&_nc_ht=scontent.fkiv3-1.fna&tp=7&oh=1df4116c73c45a32ebad070704ca3333&oe=5F6ECD77'
  }

  const saveUserToDB = async (user) => {
    console.log(user);
    await API.graphql(graphqlOperation(createUser, { input: user }))
  }

  useEffect(() => {
    const updateUser = async () => {
      // Get current authenticated user
      const userInfo = await Auth.currentAuthenticatedUser({ bypassCache: true });

      if(userInfo) {
        // Check if user already exists in database
        const userData = await API.graphql(graphqlOperation(getUser, { id: userInfo.attributes.sub }));
        console.log(userData)
        if(!userData.data.getUser) {
          const user = {
            id: userInfo.attributes.sub,
            username: userInfo.username,
            name: userInfo.username,
            email: userInfo.attributes.email,
            image: getRandomImage(),
          }
          await saveUserToDB(user);
        } else {
          console.log('User already exists');
        }
      }


      // If it doesn't, create the user in the database
    }
    updateUser();
  }, [])

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      <SafeAreaProvider>
        <Navigation colorScheme={colorScheme} />
        <StatusBar />
      </SafeAreaProvider>
    );
  }
}
Example #15
Source File: habit-actions.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
handleHabitsFromCloudWhenLoggingIn = (
  userId: string,
  merge: boolean
): AppThunk => async (dispatch, getState) => {
  const variables: {
    filter: ModelHabitFilterInput
    limit?: number
    nextToken?: string
  } = {
    filter: {
      userId: {
        eq: userId
      }
    }
  }

  try {
    const response = (await API.graphql(
      graphqlOperation(listHabits, variables)
    )) as {
      data: ListHabitsQuery
    }
    const cloudHabits = response.data.listHabits?.items
    const resultHabits = convertRemoteHabitsToLocalHabits(cloudHabits)
    const habits = getHabitsMap(getState())

    const promiseArray = []

    // If user does want to merge, we replace habitState.habits with concatenated on-cloud habits and current habitState.habits.
    if (merge) {
      habits.forEach((localHabit: Habit) => {
        // go through responsed items and merging local habits to see if there is any habits in commons
        const commonIndex = cloudHabits?.findIndex(
          (item) => item?.title?.trim() === localHabit.title.trim()
        )

        const syncingHabit: Habit = {
          ...localHabit,
          id: '',
          userId
        }

        // if the local habit is not stored in the cloud yet, we sync and merge it
        if (commonIndex === -1) {
          syncingHabit.id = v4() // Create new id for adding to cloud

          // Perform sync here
          promiseArray.push(
            dispatch(syncHabit(MutationType.CREATE, syncingHabit))
          )
        }
        // If the local habit is stored in the cloud, we update the cloud with the latest version of it (on-device/local)
        else {
          syncingHabit.id = cloudHabits[commonIndex].id // Keep the existing id

          // Perform sync here
          promiseArray.push(
            dispatch(syncHabit(MutationType.UPDATE, syncingHabit))
          )
        }

        // Perform merge here
        resultHabits.set(syncingHabit.id, syncingHabit)
      })
    }

    // Replace habitState.subHabits with old habitState.habits
    promiseArray.push(dispatch(replaceSubHabits(habits)))
    // Replace current habitState.habits with the result map
    promiseArray.push(dispatch(replaceHabits(resultHabits)))
    await Promise.all(promiseArray)
  } catch (error) {
    Sentry.captureException(error)

    await dispatch(toggleMergingDialog(false))
  }
}
Example #16
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
App = () => {
  const [formState, setFormState] = useState(initialState);
  const [todos, setTodos] = useState<any[]>([]);

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

  const setInput = (key: any, value: any):any => {
    setFormState({ ...formState, [key]: value });
  }

  const fetchTodos = async (): Promise<any> => {
    try {
      const todoData:any = await API.graphql(graphqlOperation(listTodos));
      const todos:any = todoData.data.listTodos.items;
      setTodos(todos);
    } catch (err) { 
      console.log('error fetching todos');
    }
  }

  const addTodo = async (): Promise<any> => {
    try {
      if (!formState.name || !formState.description) return;
      const todo = { ...formState };
      setTodos([...todos, todo] as SetStateAction<any[]>);
      setFormState(initialState);
      await API.graphql(graphqlOperation(createTodo, {input: todo}));
    } catch (err) {
      console.log('error creating todo:', err);
    }
  }

  return (
    <View style={styles.container}>
      <TextInput
        onChangeText={val => setInput('name', val)}
        style={styles.input}
        value={formState.name} 
        placeholder="Name"
      />
      <TextInput
        onChangeText={val => setInput('description', val)}
        style={styles.input}
        value={formState.description}
        placeholder="Description"
      />
      <Button title="Create Todo" onPress={addTodo} />
      {
        todos.map((todo, index) => (
          <View key={todo.id ? todo.id : index} style={styles.todo}>
            <Text style={styles.todoName}>{todo.name}</Text>
            <Text>{todo.description}</Text>
          </View>
        ))
      }
    </View>
  )
}
Example #17
Source File: index.tsx    From aws-appsync-iot-core-realtime-dashboard with MIT No Attribution 4 votes vote down vote up
MapPage: React.FC = () => {

    const history = useHistory();

    useEffect(() => {

        var map : Map;

        function sensorClicked (sensorId: string){
            var sensorImage = document.getElementById('sensor-image-' + sensorId);
    
            if (sensorImage) {
                history.push('/sensor/' + sensorId);
                console.log(sensorId + ' clicked');
            }
        }

        // call api to get list of sensors and display them as markers on the map
        async function  DisplaySensors(map : Map){

            const response = await GetSensors();
    
            if (response) {
    
                console.log('sensors retrived');
                
                response.forEach( (sensor) => {
    
                    var marker = GetSensorMarker(sensor.sensorId, sensor.status, () => sensorClicked(sensor.sensorId)) 
    
                    new Marker(marker)
                        .setLngLat([sensor.geo.longitude, sensor.geo.latitude])
                        .addTo(map);
                })
            }
        }

        // configure and display the map
        async function initializeMap() {

            try {

                //draw map
                map = await createMap({
                    container: "map",
                    center: [-122.2000, 37.70000],
                    zoom: 10, 
                    maxZoom: 11
                })
 
                map.repaint = true;

                console.log('Map Rendered')

                await DisplaySensors(map)

            }
            catch (error) {
                console.log('error fetching sensors', error);
            }

        }
        
        initializeMap();
    
        return () => {
            map.remove()
            console.log('map unloaded')
        };

    }, [history]);

    // start subscription for sensor status changes and update sensor marker color
    useEffect(() => {

        // @ts-ignore
        const subscription = API.graphql(graphqlOperation(onCreateSensorValues)).subscribe({
            next: (response: ISensorsSubscriptionResponse) => {
                console.log('sensor subscription value received')
                UpdateSensorMarker(response.value.data.onCreateSensorValues.sensorId, response.value.data.onCreateSensorValues.status)
            },
            error: (error: any) => console.warn(error),
         });
      
        return () => {
            subscription.unsubscribe()
            console.log('subscription cancelled')
        };
    }, []);


    return (
        <Box margin={{ bottom: "l", top: "s" }} padding="xxs">
            <SpaceBetween size="m">
                <Header variant="h1">
                    Bay Health
                </Header>
                <Container>
                    <div id='map'/>
                </Container>
            </SpaceBetween>
        </Box>
    )
}
Example #18
Source File: index.tsx    From TwitterClone with MIT License 4 votes vote down vote up
Footer = ({ tweet }: FooterContainerProps) => {

  console.log(tweet);

  const [user, setUser] = useState(null);
  const [myLike, setMyLike] = useState(null);
  const [likesCount, setLikesCount] = useState(tweet.likes.items.length);

  useEffect(() => {
    const fetchUser = async () => {
      const currentUser = await Auth.currentAuthenticatedUser();
      setUser(currentUser);

      const searchedLike = tweet.likes.items.find(
        (like) => like.userID === currentUser.attributes.sub
      );
      setMyLike(searchedLike);
    }
    fetchUser();
  }, [])

  const submitLike = async () => {
    const like = {
      userID: user.attributes.sub,
      tweetID: tweet.id,
    }

    try {
      const res = await API.graphql(graphqlOperation(createLike, { input: like }))
      setMyLike(res.data.createLike);
      setLikesCount(likesCount + 1);
    } catch (e) {
      console.log(e);
    }
  }

  const removeLike = async () => {
    try {
      await API.graphql(graphqlOperation(deleteLike, { input: { id: myLike.id } }))
      setLikesCount(likesCount - 1);
      setMyLike(null);
    } catch (e) {
      console.log(e);
    }
  }

  const onLike = async () => {
    if (!user) {
      return;
    }

    if (!myLike) {
      await submitLike()
    } else {
      await removeLike();
    }

  }

  return (
    <View style={styles.container}>
      <View style={styles.iconContainer}>
        <Feather name={"message-circle"} size={20} color={'grey'}/>
        <Text style={styles.number}>{tweet.numberOfComments}</Text>
      </View>
      <View style={styles.iconContainer}>
        <EvilIcons name={"retweet"} size={28} color={'grey'}/>
        <Text style={styles.number}>{tweet.numberOfRetweets}</Text>
      </View>
      <View style={styles.iconContainer}>
        <TouchableOpacity onPress={onLike}>
          <AntDesign name={!myLike ? "hearto" : "heart"} size={20} color={!myLike ? 'grey' : 'red'}/>
        </TouchableOpacity>
        <Text style={styles.number}>{likesCount}</Text>
      </View>
      <View style={styles.iconContainer}>
        <EvilIcons name={"share-google"} size={28} color={'grey'}/>
      </View>
    </View>
  )
}
Example #19
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 4 votes vote down vote up
App = () => {
  const defaultPostState = { id: "", title: "", content: "" };
  // Post
  const [postState, setPostState] = useState(defaultPostState);
  const [posts, setPosts] = useState([]);
  // Create post section
  const [createSectionState, setCreateSectionState] = useState(true);
  // Update post section
  const [updateSectionState, setUpdateSectionState] = useState(false);

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

  const fetchPosts = async (): Promise<any> => {
    try {
      console.log("fetching posts");
      const postData: any = await API.graphql(
        graphqlOperation(queries.listPosts)
      );
      const posts: any = postData.data.listPosts.items;
      setPosts(posts);
    } catch (err) {
      console.log("error fetching posts: ", err);
    }
  };

  const createSubscription: any = API.graphql(
    graphqlOperation(subscriptions.onCreatePost)
  );
  createSubscription.subscribe({
    next: (postData: any) => {
      console.log("onCreatePost", postData);
      fetchPosts();
    },
  });

  const updateSubscription: any = API.graphql(
    graphqlOperation(subscriptions.onUpdatePost)
  );
  updateSubscription.subscribe({
    next: (postData: any) => {
      console.log("onUpdatePost", postData);
      fetchPosts();
    },
  });
  const deleteSubscription: any = API.graphql(
    graphqlOperation(subscriptions.onDeletePost)
  );
  deleteSubscription.subscribe({
    next: (postData: any) => {
      console.log("onDeletePost", postData);
      fetchPosts();
    },
  });

  const setInput = (key: any, value: any): any => {
    setPostState({ ...postState, [key]: value });
  };

  const createPost = async (): Promise<any> => {
    try {
      if (!postState.title || !postState.content) return;
      const post = { ...postState };
      console.log("creating post", post);
      const result = await API.graphql(
        graphqlOperation(mutations.createPost, {
          input: { title: post.title, content: post.content },
        })
      );
      setPosts([...posts, post] as SetStateAction<never[]>);
      setPostState(defaultPostState);
      console.log("created post", result);
    } catch (err: any) {
      console.log("error creating post:", err);
    }
  };

  const updatePost = async (): Promise<any> => {
    try {
      if (!postState.title || !postState.content) return;
      const post = { ...postState };
      console.log("updating post", post);
      const result = await API.graphql(
        graphqlOperation(mutations.updatePost, {
          input: {
            id: post.id,
            title: post.title,
            content: post.content,
          },
        })
      );
      setUpdateSectionState(false);
      setCreateSectionState(true);
      console.log("updated post", result);
      setPostState(defaultPostState);
    } catch (err: any) {
      console.log("error updating post:", err);
    }
  };

  const deletePost = async (postID: string): Promise<any> => {
    try {
      if (!postID) return;
      console.log("deleting post", postID);
      const result = await API.graphql(
        graphqlOperation(mutations.deletePost, {
          input: {
            id: postID,
          },
        })
      );
      console.log("deleted post", result);
    } catch (err: any) {
      console.log("error deleting post:", err);
    }
  };

  const findPosts = async (title: string): Promise<any> => {
    try {
      console.log("finding posts:", title);
      const postData: any = await API.graphql(
        graphqlOperation(queries.listPosts, {
          filter: {
            title: {
              contains: title,
            },
          },
        })
      );
      console.log("found posts:");
      const posts: any = postData.data.listPosts.items;
      setPosts(posts);
    } catch (err) {
      console.log("error finding posts ", err);
    }
  };

  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.container}>
        <TextInput
          onChangeText={(val) => findPosts(val)}
          style={styles.input}
          placeholder="Search"
        />

        {createSectionState ? (
          <View>
            <Text style={styles.title}>Create Post</Text>
            <TextInput
              onChangeText={(val) => setInput("title", val)}
              style={styles.input}
              value={postState.title}
              placeholder="Title"
            />
            <TextInput
              onChangeText={(val) => setInput("content", val)}
              style={styles.textArea}
              value={postState.content}
              placeholder="Content"
            />
            <Text style={styles.button} onPress={createPost}>
              Create Post
            </Text>
          </View>
        ) : null}

        {updateSectionState ? (
          <View>
            <Text style={styles.title}>Update Post</Text>
            <TextInput
              onChangeText={(val) => setInput("title", val)}
              style={styles.input}
              value={postState.title}
              placeholder="Title"
            />
            <TextInput
              onChangeText={(val) => setInput("content", val)}
              style={styles.textArea}
              value={postState.content}
              placeholder="Content"
            />
            <Text style={styles.button} onPress={updatePost}>
              Update Post
            </Text>
          </View>
        ) : null}

        <ScrollView style={styles.scrollView}>
          {posts.map((post: any, index: any) => (
            <View key={post.id ? post.id : index} style={styles.post}>
              <Text style={styles.postTitle}>{post.title}</Text>
              <Text style={styles.postContent}>{post.content}</Text>

              <View style={{ flexDirection: "row" }}>
                <Text
                  style={styles.postUpdate}
                  onPress={() => {
                    setPostState(post);
                    setUpdateSectionState(true);
                    setCreateSectionState(false);
                  }}
                >
                  Update
                </Text>
                <Text
                  style={styles.postDelete}
                  onPress={() => {
                    deletePost(post.id);
                  }}
                >
                  Delete
                </Text>
              </View>
            </View>
          ))}
        </ScrollView>
      </View>
    </SafeAreaView>
  );
}
Example #20
Source File: index.tsx    From SpotifyClone with MIT License 4 votes vote down vote up
PlayerWidget = () => {

  const [song, setSong] = useState(null);
  const [sound, setSound] = useState<Sound|null>(null);
  const [isPlaying, setIsPlaying] = useState<boolean>(true);
  const [duration, setDuration] = useState<number|null>(null);
  const [position, setPosition] = useState<number|null>(null);

  const { songId } = useContext(AppContext);

  useEffect(() => {
    const fetchSong = async () => {
      try {
        const data = await API.graphql(graphqlOperation(getSong, { id: songId }))
        setSong(data.data.getSong);
      } catch (e) {
        console.log(e);
      }
    }

    fetchSong();
  }, [songId])

  const onPlaybackStatusUpdate = (status) => {
    setIsPlaying(status.isPlaying);
    setDuration(status.durationMillis);
    setPosition(status.positionMillis);
  }

  const playCurrentSong = async () => {
    if (sound) {
      await sound.unloadAsync();
    }

    const { sound: newSound } = await Sound.createAsync(
      { uri: song.uri },
      { shouldPlay: isPlaying },
      onPlaybackStatusUpdate
    )

    setSound(newSound)
  }

  useEffect(() => {
    if (song) {
      playCurrentSong();
    }
  }, [song])

  const onPlayPausePress = async () => {
    if (!sound) {
      return;
    }
    if (isPlaying) {
      await sound.stopAsync();
    } else {
      await sound.playAsync();
    }
  }

  const getProgress = () => {
    if (sound === null || duration === null || position === null) {
      return 0;
    }

    return (position / duration) * 100;
  }

  if (!song) {
    return null;
  }

  return (
    <View style={styles.container}>
      <View style={[styles.progress, { width: `${getProgress()}%`}]} />
      <View style={styles.row}>
        <Image source={{ uri: song.imageUri }} style={styles.image} />
        <View style={styles.rightContainer}>
          <View style={styles.nameContainer}>
            <Text style={styles.title}>{song.title}</Text>
            <Text style={styles.artist}>{song.artist}</Text>
          </View>

          <View style={styles.iconsContainer}>
            <AntDesign name="hearto" size={30} color={"white"}/>
            <TouchableOpacity onPress={onPlayPausePress}>
              <FontAwesome name={isPlaying ? 'pause' : 'play'} size={30} color={"white"}/>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </View>
  )
}
Example #21
Source File: index.tsx    From aws-appsync-iot-core-realtime-dashboard with MIT No Attribution 4 votes vote down vote up
SensorPage: React.FC = () => {

    const sensorTypes = GetSensorTypes()

    const [selectedSensor, setSelectedSensor] = useState("temperature");
    const [name, setName] = useState("Fetching sensor data...");
    const [value, setValue] = useState<ISensorSubscriptionResponse | null>(null);

    const { id } = useParams() as { 
        id: string;
    }

    const GetSelectedValue = () : number | null | undefined => {

        let n: number | null | undefined = null;

        let v = value?.value.data.onCreateSensorValue

        if (selectedSensor === 'temperature') {
            n = v?.temperature
        } else if (selectedSensor === 'salinity') {
            n = v?.salinity
        } else if (selectedSensor === 'disolvedO2') {
            n = v?.disolvedO2
        } else if (selectedSensor === 'ph') {
            n = v?.pH
        }

        return n;
    }

    //fetch sensor to get name
    useEffect(() => {

            const initSensor = async () => {
            
            console.log('fetching sensor');

            try {

                const response = await GetSensor(id || "");

                if (response) {
                    setName(response.name);
                    console.log('sensor retrived');
                }
            }
            catch (error) {
                console.log('error fetching sensor', error);
            }
        };

        initSensor()

    }, [id]);
    
    // start subscription for sensor value changes
    useEffect(() => {

        // @ts-ignore
        const subscription = API.graphql(graphqlOperation(onCreateSensorValue, {sensorId: id})).subscribe({
            next: (response: ISensorSubscriptionResponse) => {
                console.log('sensor value received')
                setValue(response)
            },
            error: (error: any) => console.warn(error),
         });
      
        return () => {
            subscription.unsubscribe()
            console.log('subscription cancelled')
        };
    }, [id]);

    return (
        <Box margin={{ bottom: "l", top: "s" }} padding="xxs">
            <BreadcrumbGroup
                items={[
                    { text: "Sensor Map", href: "#" },
                    { text: "Sensor", href: "#sensor" },
                ]}
                ariaLabel="Breadcrumbs"
            />
            <Header variant="h1"
            actions={
                <SegmentedControl
                    selectedId={selectedSensor}
                    onChange={({ detail }) => {
                        setValue(null)
                        setSelectedSensor(detail.selectedId)
                        }
                    }
                    label="Sensor Values"
                    options={sensorTypes}
              />
            }
            >
                {name}
            </Header>
            <SpaceBetween size="xl">
                <SensorValuePanel value={GetSelectedValue()} />
                <SensorChart title={selectedSensor} value={GetSelectedValue()}/>
            </SpaceBetween>
        </Box>
    )
}
Example #22
Source File: NewTweetScreen.tsx    From TwitterClone with MIT License 4 votes vote down vote up
export default function NewTweetScreen() {

  const [tweet, setTweet] = useState("");
  const [imageUrl, setImageUrl] = useState("");

  const navigation = useNavigation();

  const getPermissionAsync = async () => {
    if (Platform.OS !== 'web') {
      const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  };

  useEffect(() => {
    getPermissionAsync()
  }, [])

  const pickImage = async () => {
    try {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
      });
      if (!result.cancelled) {
        setImageUrl(result.uri);
      }

      console.log(result);
    } catch (E) {
      console.log(E);
    }
  };

  const uploadImage = async () => {
    try {
      const response = await fetch(imageUrl);

      const blob = await response.blob();

      const urlParts = imageUrl.split('.');
      const extension = urlParts[urlParts.length - 1];

      const key = `${uuidv4()}.${extension}`;

      await Storage.put(key, blob);

      return key;

    } catch (e) {
      console.log(e);
    }
    return '';
  }

  const onPostTweet = async () => {
    let image;
    if (!!imageUrl) {
      image = await uploadImage();
    }

    try {
      const currentUser = await Auth.currentAuthenticatedUser({ bypassCache: true });

      const newTweet = {
        content: tweet,
        image,
        userID: currentUser.attributes.sub,
      }
      await API.graphql(graphqlOperation(createTweet, { input: newTweet }));
      navigation.goBack();
    } catch (e) {
      console.log(e);
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.headerContainer}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <AntDesign name="close" size={30} color={Colors.light.tint} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.button} onPress={onPostTweet}>
          <Text style={styles.buttonText}>Tweet</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.newTweetContainer}>
        <ProfilePicture image={'https://scontent.fkiv3-1.fna.fbcdn.net/v/t31.0-8/s960x960/22256588_1932617800312085_5686197942193420542_o.jpg?_nc_cat=110&_nc_sid=85a577&_nc_ohc=svjjE7DUkc0AX9yjcdC&_nc_ht=scontent.fkiv3-1.fna&tp=7&oh=1df4116c73c45a32ebad070704ca3333&oe=5F6ECD77'}/>
        <View style={styles.inputsContainer}>
          <TextInput
            value={tweet}
            onChangeText={(value) => setTweet(value)}
            multiline={true}
            numberOfLines={3}
            style={styles.tweetInput}
            placeholder={"What's happening?"}
          />
          <TouchableOpacity onPress={pickImage}>
            <Text style={styles.pickImage}>Pick a image</Text>
          </TouchableOpacity>
          <Image source={{ uri: imageUrl }} style={styles.image} />
        </View>
      </View>
    </SafeAreaView>
  );
}