DEV Community

Discussion on: How to create a custom React hook to fetch an API (using TypeScript)?

Collapse
 
elyasthr profile image
Elyas

what is the use of coding with ts to put any at data, precisely I would like to know what to put in place of any so that it works in strict mode

Collapse
 
brian1150 profile image
Brian-1150

@elyas This hook is meant to be used by reused by various components or functions. By design, it can accept any url as an argument and return any data that gets returned from that API. If you know what kind of data you are expecting to get back, you can make an interface specific for that component.

In this example we know we are expecting to get back movie info and we can adjust the App component like this:

import React, { useEffect, useState } from 'react'
import { useApiGet, TApiResponse } from '../hooks/useApiHook'

interface Movie {
    Released: string;
    Response: string;
    Runtime: string;
    Title: string;
    Type: string;
    Website: string;
    Writer: string;
    Year: string;
    imdbID: string;
    imdbRating: string;
    imdbVotes: string;
    Actors: string;
    Awards: string;
    BoxOffice: string;
    Country: string;
    DVD: string;
    Director: string;
    Genre: string;
    Language: string;
    Metascore: string;
    Plot: string;
    Poster: string;
    Production: string;
    Rated: string;
}
function Test() {
    const [data, dataSet] = useState<Movie>({} as Movie);
    const testData: TApiResponse = useApiGet(
        // 'http://www.omdbapi.com/?s=Guardians&apikey=xxxxxxxx'
        'http://www.omdbapi.com/?t=GoodFellas&apikey=1fcaeb08'
    )

    useEffect(() => {
        if (testData) {
            dataSet((testData.data) as Movie);
        }

    }, [testData])
    console.log(data);

    return (
        <div>
            {data && <div>{data.Title} was released in {data.Year}</div>}
        </div>
    );
}

export default Test;
Enter fullscreen mode Exit fullscreen mode

The same thing can be done for any API returning "any" kind of data.

Collapse
 
dzienisz profile image
Kamil Dzieniszewski

setData not dataSet