[英]How to use custom hook (fetch) with typescript
I have created a custom hooks called useFetch.我创建了一个名为 useFetch 的自定义钩子。
import { useState, useEffect } from 'react'
export const useFetch = (url: string, options?: object) => {
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
But destructuring useFetch
and typing it with typescript fails as if the answer may be null但是解构useFetch
并用 typescript 键入它失败,好像答案可能是 null
import React, { FunctionComponent } from 'react'
import { useFetch } from '../../hooks/useFetch'
export const ListOfMovies: FunctionComponent = () => {
const { response, error }: { response: object, error: object} = useFetch("http://www.omdbapi.com/?apikey=****&s=batman&page=2")
if (!response) return <h2>Loading...</h2>
if (error) return <h2>Error</h2>
return (
<div>
<h2>Lista de películas</h2>
{response.Search.map(movie => (
<p>{movie.Title}</p>
))}
</div>
)
}
import { useState, useEffect } from 'react'
export const useFetch = (url: string, options?: object) => {
const [response, setResponse] = useState<any>(null);
const [error, setError] = useState<any>(null);
...
};
... ...
If you don't like 'any' try using generic.如果您不喜欢“任何”,请尝试使用泛型。
export const useFetch = <T>(url: string, options?: object) => { const [response, setResponse] = useState<T>(null); const [error, setError] = useState<T>(null); ... };
} }
So the function invocation will look like所以 function 调用看起来像
type YourCustomType = {response: ..., error: ...}
const { response, error }: { response: object, error: object} =
useFetch<YourCustomType>("http://www.omdbapi.com/?apikey=****&s=batman&page=2");
}
You have set the initial value of response and error as null therefore you are getting this warning.您已将响应和错误的初始值设置为 null,因此您收到此警告。
Try this:尝试这个:
const [response, setResponse] = useState({});
const [error, setError] = useState({});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.