copenndthagen
copenndthagen

Reputation: 50722

Return function from inside custom hook

I have the below custom hook;

export default function useFetch(url) {
    const [response, setResponse] = useState();
    useEffect(() => {
        const fetchresponse = async () => {
            // code to fetch response from api
        }
        fetchresponse();
    }, [url]);

    return [response];
}

While the above works fine from the start of my functional component, I want to make this reusable and invoke them from other places in my main component (e.g. button click) i.e. hit api on button click. Thus, I want to return an executable function, which can be invoked on say button click.

How can I do that and considering I have a useEffect here inside my custom hook ?

Upvotes: 1

Views: 3688

Answers (1)

Quentin
Quentin

Reputation: 943142

Just define the function outside the useEffect hook.

Then it will be in scope to return.

function useFetch(url) {
    const [response, setResponse] = useState();

    const fetchresponse = async () => {
        // code to fetch response from api
    }

    useEffect(() => {
        fetchresponse();
    }, [url]);

    return [response, fetchresponse];
}

Optionally wrap the function in useCallback so it doesn't get redefined with each render.

Upvotes: 3

Related Questions