Reputation:
I made state in redux hooks I don't know how to import or useSelector the state I want
Here I am using the useSelector Send to state in Login file
function Login(props) {
var classes = useStyles();
var dispatch = useDispatch();
const { username, password } = useSelector((state) => ({
...state.combineReducers,
...state.userReducer,
}));
And that is nav file And here I want to get what's in the state
function nav(props) {
const { username } = useSelector((state) => ({
...state.combineReducers,
...state.userReducer,
}));
The error
Failed to compile.
./src/NAVBAR/nav.js
Line 27: React Hook "useSelector" is called in function "nav" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
I have tried in many ways but it fails
Upvotes: 2
Views: 14467
Reputation: 74
I have faced a similar problem and found a simple solution.
const username = useSelector(state => state.userReducer.username)
so, we have taken specific username state from the reducer. This work for me:)
Upvotes: 1
Reputation: 53874
The problem is that nav
is a function and not a function-component.
In your case, you may want to make a custom-hook
:
function useUsername() {
const { userName } = useSelector(state => ({
...state.combineReducers,
...state.userReducer
}));
return { userName };
}
function Login(props) {
const { userName } = useUsername();
return <>...</>;
}
Note that if you want to make it a function component you need to return a ReactElement
and be in scope with React
import.
import React from 'react';
// v Note that you must have an Upper-case for it to be a valid ReactElement
function Nav(props) {
const { username } = useSelector(state => ({
...state.combineReducers,
...state.userReducer
}));
// return ReactElement
return <>I'm some Element</>;
}
export default Nav;
Upvotes: 6