Reputation: 313
Couldn't find react native related help to the issue in previous posts.
I'm getting this message :
invalid hook call. hooks can only be called inside of the body of a function component
My component is a functional component and all hooks (useState, useDispatch ) are called inside. Anyone gets this?
export default function LoginScreen (props) {
const [name, setName] = useState("");
const [message, setMessage] = useState("");
const nextScreen = () => {
// const dispatch = useDispatch();
// dispatch(SendMessage(name, message));
props.navigation.navigate("Chat", { name: name });
return null
};
return (
<View>
<TextInput
style={styles.input}
placeholder="name..."
onChangeText={userInput => {
console.log(userInput);
setName({ userInput });
}}
value={name}
/>
<TextInput
style={styles.input}
placeholder="message..."
onChangeText={userInput => {
console.log(userInput);
setMessage({ userInput });
}}
value={message}
/>
<View style={{ alignItems: "flex-end", marginTop: 64 }}>
<TouchableOpacity style={styles.nextScreen} onPress={nextScreen}>
<Ionicons name="md-arrow-round-forward" size={24} color="#FFF" />
</TouchableOpacity>
</View>
</View>
);
};
Upvotes: 0
Views: 2251
Reputation: 192252
The Rules of Hooks states:
Only Call Hooks at the Top Level
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
Call the hook in the body of the LoginScreen
component, and the dispatch
inside the nextScreen
function:
export default function LoginScreen(props) {
const [name, setName] = useState("");
const [message, setMessage] = useState("");
const dispatch = useDispatch(); // call hook and get dispatch
const nextScreen = () => {
dispatch(SendMessage(name, message)); // use dispatch
props.navigation.navigate("Chat", {
name: name
});
return null
};
Upvotes: 1