Reputation: 4504
I am running my react-native app but getting error such as: Can't find variable : dispatch. I am using reducer for managing different states in this app ! Any help will be appreciated!
import React, {useReducer} from 'react';
import {Button, Text, View} from 'react-native';
const reducer = (state, action) => {
switch (action.colorToChange) {
case 'red':
return {...state, red: state.red + action.amount};
case 'green':
return {...state, green: state.green + action.amount};
case 'blue':
return {...state, blue: state.blue + action.amount};
default:
return state;
}
};
const HomeScreen = () => {
const [state, action] = useReducer(reducer, {red: 0, green: 0, blue: 0});
const {red, green, blue} = state;
return (
<View>
<Button title="Red" onPress=() => {dispatch({colorToChange: 'red', amount: 1})}/>
<Button title="Green" onPress={() => dispatch({colorToChange: 'green', amount: 1})}/>
<Button title="Blue" onPress={() => dispatch({colorToChange: 'blue', amount: 1})}/>
<Text>Red Color:{red}</Text>
<Text>Green Color:{green}</Text>
<Text>Blue Color:{blue}</Text>
</View>
);
};
export default HomeScreen;
Upvotes: 0
Views: 1473
Reputation: 803
useReducer returns the dispatch as the second element of the destructured array in your case it's named action, you should change your use reducer line to
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
after this you will be able to use dispatch.. you can use it now by invoking action().. but the naming seems quite wrong
Upvotes: 2
Reputation: 3805
The second variable is the dispatch from useReducer
, so it should be as
const [state, dispatch] = useReducer(reducer, {red: 0, green: 0, blue: 0});
Upvotes: 1