0

I want use custom hook function

custom hook code

import { useState, useCallback, useEffect } from 'react';
import { apiClient } from './apiClient';

export default (api: string) => {
  const [data, setData] = useState();

  const getData = useCallback(async () => {
    try {
      const response = await apiClient.get(api);
      setData(response.data);
    } catch (err) {
      console.log(err);
    }
  }, [data]);

  return [data, getData];
};

app code

const [data, getData] = useGetData('posts');

  useEffect(() => {
    getData(); <- error
  }, []);

error message

Cannot invoke an object which is possibly 'undefined'.ts(2722)

How can use custom hook function ?

2
  • 2
    What's the error it's giving you ? Commented Jul 8, 2021 at 8:13
  • Cannot invoke an object which is possibly 'undefined'.ts(2722) this error message... Commented Jul 8, 2021 at 8:17

1 Answer 1

2

You will need to explicitly type the function to return a 2-tuple, since TypeScript can't perfectly infer that. It infers an array.

export default (api: string): [any, () => void] => {

(or a better type than any, but I don't know what your API returns.)

To improve typing, you might want to make it a generic function:

import { useState, useCallback } from "react";

export default function useGetData<T>(api: string): [T | undefined, () => void] {
  const [data, setData] = useState<T | undefined>(undefined);
  const getData = useCallback(async () => {
    try {
      const response = await apiClient.get(api);
      setData(response.data as T);
    } catch (err) {
      console.log(err);
    }
  }, [data]);
  return [data, getData];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.