S
S
Sergey Chazov2020-05-16 13:08:49
React
Sergey Chazov, 2020-05-16 13:08:49

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>
    );
}


I want pushFrom to make a request to the server, get a response and update the state (which works on Redux).

I moved pushForm() into a separate function. It makes a request to the server and returns a token (I cut the code so that only the essence remains)

function pushForm() {
const service = new AuthService;
    service.authorizeUserAction(body).then(
        ({token}) => {
            return token;
        }
    )
}


And now I need to dispatch it to the state.
I created another function
function dispatchUserInfo( token){
const userListSelector = useSelector(state => state.userList, shallowEqual);
    const dispatch            = useDispatch();
    useEffect(
        () => {
            dispatch(userTokenAction(token));
        },[]
    );
}


And I'm trying to call it from pushForm(). The IDE tells me that I am not returning anything, so hooks cannot be used https://w6p.ru/NzRlZjA.jpg And I have nothing to return.
()). But how then to build such a code correctly? Help me please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
paoluccio, 2020-05-16
@chazovs

And I'm trying to call it from pushForm()

it's against the rules , hooks should live at the top level in components or other (custom) hooks.
In your case, as one of the options, the form processing logic can be put into a custom hook. Then use it in LoginUser.
Approximate structure:
// 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>
  );
};

V
Vladimir, 2020-05-16
@Casufi

The IDE is correct.
In general, the simplest thing that can be used for asynchronous redux is https://github.com/reduxjs/redux-thunk
https://codesandbox.io/s/late-violet-m53z4?file=/s...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question