Create custom hook without passing props in React with Typescript

Viewed 1632

I'm new to learning React with Typescript and so far, I have read a lot about typing props and I just don't understand how to create a custom hook without having to pass props, here's an example:

import { useState, useEffect, FunctionComponent, ReactElement } from 'react';
import axios from 'axios';

interface PostData {
    userId: number,
    id: number,
    title: string,
    body: string
}


const usePosts = () => {
  const [posts, setPosts] = useState<PostData[]>([]);

  const getPosts = () => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(response => {
      console.log(response);
    })
    .catch(error => {
      console.error(error);
      
    })
  };

  useEffect(() => {
    getPosts();
  }, []);

  return {
    posts,
  };
};

export default usePosts;

In this case, ESlint is saying that const usePosts = () => ... is Missing return type on function.

1 Answers

you can try this (I cut your exemple in multiple file for more clarity):
your hooks just add the return type like this:
usePost.hook.tsx


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

interface PostData {
    userId: number,
    id: number,
    title: string,
    body: string
}


const usePosts = ():PostData[] => {
  const [posts, setPosts] = useState<PostData[]>([]);

  const getPosts = () => {
    axios.get<PostData[]>('https://jsonplaceholder.typicode.com/posts')
    .then(response => {
      console.log(response.data)
     setPosts(response.data)
    })
    .catch(error => {
      console.error(error);
      
    })
  };

  useEffect(() => {
    getPosts();
  }, []);

  return posts;
};

export default usePosts;

you can see an exemple of your code in this sandBox

Related