Giter Site home page Giter Site logo

aws-amplify-react-hooks's Introduction

Cover

aws-amplify-react-hooks

AWS Amplify react-native hooks (Only React Native)

Installation

npm install aws-amplify-react-hooks

Or if using yarn

yarn add aws-amplify-react-hooks

Example

git clone [email protected]:react-native-village/aws-amplify-react-hooks.git
cd examples/reactNativeCRUD
yarn
react-native run-ios
react-native run-android

API

AmplifyProvider

useQuery

useMutation

AmplifyProvider

Similar to ApolloProvider from react-apollo. In order for this package to work, you need to wrap your component tree with AmplifyProvider at an appropriate level, encapsulating all components which will use hooks.

Usage

import React from 'react'
import { AmplifyProvider } from 'aws-amplify-react-hooks'  
import { Auth, API, graphqlOperation } from 'aws-amplify'

const client = {
  Auth,
  API,
  graphqlOperation
}

AmplifyProvider(client)

const App = () => (
  <AmplifyProvider client={client}>
    <AppNavigator />
  </AmplifyProviderc>
)

render(<App />, document.getElementById('root'))

useQuery

const { 
  data: Array<mixed>,
  loading: string,
  error: string,
  fetchMore: function
} = useQuery(query {}, options: { variables: {[key: string]: any }}, queryData: Array<string>)

query - The first argument is a GraphQL query READ operation, the second is a CREATE subscription operation, the third is an UPDATE subscription operation and the fourth is a DELETE subscription operation.

option - An object containing all the variables that your request should fulfill.

queryData - An array of GraphQL operation names in the READ, CREATE, UPDATE, DELETE sequence.

data โ€” The returned data array.

loading - Loading indicator.

error - Error.

fetchMore - Often in your application there will be some views in which you need to display a list that contains too much data so that it can either be retrieved or displayed immediately. Pagination is the most common solution to this problem, and the useQuery hook has built-in functionality that makes it pretty simple. The easiest way to do pagination is to use the fetchMore function, which is included in the result object returned by the useQuery hook. This basically allows you to make a new GraphQL query and combine the result with the original result.

Simple example

import React from 'react'
import { View, Text } from 'react-native'
import { useQuery, getNames } from 'aws-amplify-react-hooks'
import { listJobs } from '../../graphql/queries' // from Amplify autogenerate file
import { onCreateJob, onUpdateJob, onDeleteJob } from '../../graphql/subscriptions' // from Amplify autogenerate file 


const Jobs = () => {
    const { data, loading, error } = useQuery(
    {
      listJobs,
      onCreateJob,
      onUpdateJob,
      onDeleteJob
    },
    {
      variables: { limit: 5 }
    },
    getNames({ listJobs, onCreateJob, onUpdateJob, onDeleteJob })
  )

  if (loading) {
    return <Text>Loading...</Text>
  }
  if (error) {
    return <Text>Error! {error}</Text>
  }

  return (
    <>
      {data.map(item => (
        <View key={item.id}>
          <Text>{item.position}</Text>
        </View>
      ))}
    </>
  )
}

Flatlist with pagination

import React from 'react'
import { View, Text, FlatList } from 'react-native'
import { useQuery, getNames } from 'aws-amplify-react-hooks'
import { listJobs } from '../../graphql/queries' // from Amplify autogenerate file
import { onCreateJob, onUpdateJob, onDeleteJob } from '../../graphql/subscriptions' // from Amplify autogenerate file

const Jobs = () => {
  const { data, loading, error, fetchMore } = useQuery(
    {
      listJobs,
      onCreateJob,
      onUpdateJob,
      onDeleteJob
    },
    {
      variables: { limit: 5 }
    },
    getNames({ listJobs, onCreateJob, onUpdateJob, onDeleteJob })
  )

  const _renderItem = ({ item }) => {
    return <Text>{item.position}</Text>
  }

  const _keyExtractor = obj => obj.id.toString()
  
  if (loading) {
    return <Text>Loading...</Text>
  }
  if (error) {
    return <Text>Error! {error}</Text>
  }

  return (
    <>
      <FlatList
        scrollEventThrottle={16}
        data={data}
        renderItem={_renderItem}
        keyExtractor={_keyExtractor}
        onEndReachedThreshold={0.5}
        onEndReached={fetchMore}
      />
    </>
  )
}

useMutation

const [
  setCreate: Promise<{}>,
  setUpdate: Promise<{}>,
  setDelete: Promise<{}>
{ 
  loading: string,
  error: string
}
] = useMutation(input: {})

setCreate setUpdate setDelete - Functions CREATE, UPDATE, DELETE

loading - Loading indicator.

error - Error.

input - Mutation value.

import React, { useState } from 'react' 
import { View, Text, Button } from 'react-native'

import { useMutation } from 'aws-amplify-react-hooks' 
import { createJob, updateJob, deleteJob } from '../../graphql/mutations' // from Amplify autogenerate file

const Jobs = () => {  
  const [input, setJob] = useState({
    position: '',
    rate: '',
    description: ''
  })

  const [setCreate, setUpdate, setDelete, { loading, error }] = useMutation(input)

  const onCreate = async () => {
    const obj = await setCreate(createJob)
    console.log('obj', obj)
  }
  const onUpdate = async () => (await setUpdate(updateJob))
  const onDelete = async () => (await setDelete(deleteJob))
  
  if (loading) {
    return <Text>Loading...</Text>
  }
  if (error) {
    return <Text>Error! {error}</Text>
  }
  
  return (
    <>
      <Button title="CREATE" onPress={onCreate} />
    </>
  )
}

aws-amplify-react-hooks's People

Contributors

ghashtag avatar wintus avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.