skip to Main Content

I have no other option but to call the submit method for a fetcher in a handler. It’s accessing the correct action method in the routers however I’m unable to pass the method to the action, i.e. method='POST defined in the Form. How to access the method of fetch.Form inside the handler?

const fetcher = useFetcher()

const handlerLogin = useCallback(async () => {
  console.log(fetcher.formMethod) //-> outputting undefined
  fetcher.submit({ value: 'social' }, { method: fetcher.formMethod })
},[])
    
return (
  <Card className={styles.loginCard}>
    <fetcher.Form method='POST' action='/'>
      ..............

2

Answers


  1. Try this solution, you pass the method to the handlerLogin function:

    const fetcher = useFetcher();
    
    const handlerLogin = useCallback(async (formMethod) => {
      fetcher.submit({ value: 'social' }, { method: formMethod });
    }, []);
    
    return (
      <Card className={styles.loginCard}>
        <fetcher.Form
          method='POST'
          action='/'
        >
          {/* other parts ... */}
          <button onClick={() => handlerLogin(fetcher.formMethod)}>
            Submit
          </button>
        </fetcher.Form>
      </Card>
    );
    
    Login or Signup to reply.
  2. handlerLogin is being memoized and is closing over the fetcher value from the initial render cycle. fetcher is an external dependency so it should be included in the useCallback hook’s dependency array.

    const fetcher = useFetcher();
    
    const handlerLogin = useCallback(() => {
      console.log(fetcher.formMethod);
      fetcher.submit({ value: 'social' }, { method: fetcher.formMethod });
    }, [fetcher]);
    

    Since this is likely only passed to the RRD Form component and not down as a prop to children I suspect the useCallback hook is even necessary and could likely be removed.

    const fetcher = useFetcher();
    
    const handlerLogin = () => {
      console.log(fetcher.formMethod);
      fetcher.submit({ value: 'social' }, { method: fetcher.formMethod });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search