Skip to content

Instantly share code, notes, and snippets.

@mjstelly
Created March 8, 2021 15:38
Show Gist options
  • Save mjstelly/51b0d4a83c124eac71d3ff210b0bccf9 to your computer and use it in GitHub Desktop.
Save mjstelly/51b0d4a83c124eac71d3ff210b0bccf9 to your computer and use it in GitHub Desktop.
Debugging state errors
import React, { useReducer } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import ColorCounter from '../components/ColorCounter';
const COLOR_INCREMENT = 15;
const reducer = (state, action) => {
//state === {red: number, green: number, blue: number}
//action === {colorToChange: red || green || blue, amount: 15 || -15}
switch (action.colorToChange) {
case 'red':
console.log(state);
return { ...state.red, red: state.red + action.amount };
case 'green':
console.log(state);
return { ...state.green, green: state.green + action.amount };
case 'blue':
console.log(state);
return { ...state.blue, blue: state.blue + action.amount };
default:
console.log(state);
return;
}
};
const SquareScreen = () => {
const [state, dispatch] = useReducer(reducer, { red: 0, green: 0, blue: 0 });
const { red, green, blue } = state;
return (
<View>
<ColorCounter
onIncrease={() =>
dispatch({ colorToChange: 'red', amount: COLOR_INCREMENT })
}
onDecrease={() =>
dispatch({ colorToChange: 'red', amount: -1 * COLOR_INCREMENT })
}
color="Red"
/>
<ColorCounter
onIncrease={() =>
dispatch({ colorToChange: 'blue', amount: COLOR_INCREMENT })
}
onDecrease={() =>
dispatch({ colorToChange: 'blue', amount: -1 * COLOR_INCREMENT })
}
color="Blue"
/>
<ColorCounter
onIncrease={() =>
dispatch({ colorToChange: 'green', amount: COLOR_INCREMENT })
}
onDecrease={() =>
dispatch({ colorToChange: 'green', amount: -1 * COLOR_INCREMENT })
}
color="Green"
/>
<View
style={{
height: 150,
width: 150,
backgroundColor: `rgb(${red}, ${blue}, ${green})`,
}}
/>
</View>
);
};
const styles = StyleSheet.create({
textStyle: {
fontSize: 30,
},
});
export default SquareScreen;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment