Home > Mobile >  Calling a custom hook from an onClick by passing it arguments
Calling a custom hook from an onClick by passing it arguments

Time:06-22

I created a custom hook to make my api calls with axios. When I call this hook passing it different parameters, it returns 3 states.

I created a page with a form. When I submit this form I call a function "onSubmitform" I would like to be able to execute this custom hook in this function.

How can I do ?

Maybe a custom hook is not suitable in this case?

-- file useAxios.js --

import { useState, useEffect } from "react";
import axios from "axios";

const useAxios = (axiosParams) => {
  const [response, setResponse] = useState(undefined);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  const handleData = async (params) => {
    try {
      const result = await axios.request(params);
      setResponse(result.data);
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    handleData(axiosParams);
  }, []);

  return { response, error, loading };
};

export default useAxios;

-- file Page.js --

import useAxios from "../hooks/useAxios";

function Page() {
  const { response } = useAxios();

  const onSubmitForm = () => {
    // Here I want to call the custom hook by passing it different parameters.
  }
}

CodePudding user response:

You can add an option to execute the request manually and avoid the fetch on mount:

const useAxios = (axiosParams, executeOnMount = true) => {
  const [response, setResponse] = useState(undefined);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  const handleData = async (params) => {
    try {
      const result = await axios.request(params);
      setResponse(result.data);
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (executeOnMount) handleData(axiosParams);
  }, []);

  return { response, error, loading, execute: handleData };
};

Then use it:

  const { response, execute } = useAxios(undefined, false);

  const onSubmitForm = (data) => {
    execute(params) // handleData params
  }

CodePudding user response:

A hook is a function (returning something or not) which should be called only when the components (re)renders. Here you want to use it inside a callback responding to an event, which is not the same thing as the component's render.

Maybe you are just looking for a separate, "simple", function? (for example something similar to what you have in your "useEffect")

  • Related