import {useEffect, useState} from 'react';
import {context, pageContext} from '../context';
import {useContextSection, usePage} from '@hooks';

export function useField() {
  const name = useContextSection(context, state => state[0].name);
  const [state, setState] = useState(name);

  useEffect(function() {
    setState(name);
  }, [name]);

  function onChange(val: string) {
    setState(val);
  }

  return [state, onChange] as const;
}

export function useHandle(value: string) {
  const dispatch = useContextSection(context, state => state[1]);
  const [, {onCurrentPageChange}] = usePage(pageContext);

  function onSearch() {
    onCurrentPageChange(1);
    dispatch({type: 'SEARCH', payload: {name: value}});
  }

  return {onSearch};
}
