Answer the question
In order to leave comments, you need to log in
Is it possible to move hooks into a separate function. And if not, how to be?
i have an exportable function that draws a form
export default function LoginUser() {
return (
<div>
<form id="auth_form">
<div className="form-group">
<label htmlFor="Email">Email</label>
<input type="text" className="form-control" id="email" placeholder="Email"/>
</div>
<Button autofocus="true" onClick={() => pushForm()}>Авторизоваться</Button>
</form>
</div>
);
}
function pushForm() {
const service = new AuthService;
service.authorizeUserAction(body).then(
({token}) => {
return token;
}
)
}
function dispatchUserInfo( token){
const userListSelector = useSelector(state => state.userList, shallowEqual);
const dispatch = useDispatch();
useEffect(
() => {
dispatch(userTokenAction(token));
},[]
);
}
Answer the question
In order to leave comments, you need to log in
And I'm trying to call it from pushForm()
// Custom hook
export const useAuthHandler = () => {
const [token, setToken] = useState(null);
useEffect(() => {
if (token) { // чтобы не диспатчить с начальным null на первом рендере
// диспатчим экшн с полученным токеном
}
}, [token]); // будет следить за token
return () => { // возвращаем функцию-обработчик
// запрашиваем токен, в then вызываем setToken(token)
};
};
// Component
export default function LoginUser() {
const handleSubmit = useAuthHandler();
return (
<div>
<form id="auth_form">
{/* ... */}
<Button autofocus="true" onClick={handleSubmit}>Авторизоваться</Button>
</form>
</div>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question