Skip to content

Instantly share code, notes, and snippets.

@ronal2do
Last active February 20, 2019 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronal2do/d5f4bdbbcc1b5fc5f52497f32d9413ab to your computer and use it in GitHub Desktop.
Save ronal2do/d5f4bdbbcc1b5fc5f52497f32d9413ab to your computer and use it in GitHub Desktop.
import React, { useReducer, useContext, ReactNode } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'
const initialArg = 0
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'set'; count: number }
const reducer = (state: number, action: Action) => {
switch (action.type) {
case 'increment': return state + 1
case 'decrement': return state - 1
case 'set': return action.count
default: throw new Error('Unexpected action')
}
}
const Context = React.createContext(initialArg as any)
const CountProvider = ({ children }: { children: ReactNode }) => {
const contextValue = useReducer(reducer, initialArg)
return (
<Context.Provider value={contextValue}>
{children}
</Context.Provider>
)
}
const useCount = () => {
const contextValue = useContext(Context)
return contextValue
}
const Counter = () => {
const [count, dispatch] = useCount()
return (
<View style={styles.container}>
<Text>{count}</Text>
<View style={styles.buttons}>
<TouchableOpacity
style={styles.button}
onPress={() => dispatch({ type: 'increment' })
}>
<Text>+1</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => dispatch({ type: 'decrement' })
}>
<Text>-1</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => dispatch({ type: 'set', count: 0 })
}>
<Text>reset</Text>
</TouchableOpacity>
</View>
</View>
)
}
export default function App() {
return (
<CountProvider>
<Counter />
</CountProvider>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
buttons: {
flexDirection: 'row',
justifyContent: 'space-between',
},
button: {
padding: 20,
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment