I have a question about the implementation useFetch hook with typescript and Axios.
Here is I find some example useFetch hook. But It's a javascript implementation. I just gave there any to response and err.
https://codesandbox.io/s/react-fetch-hook-gtiec?from-embed=&file=/src/components/App.js
so here is my useFetch hook .ts file.
import { useState, useEffect } from 'react'
export const useFetch = ({
api,
method,
url,
data = null,
config = null,
}: any) => {
const [response, setResponse] = useState(null)
const [error, setError] = useState('')
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
const fetchData = async () => {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res : any) => {
setResponse(res.data)
})
.catch((err : any) => {
setError(err)
})
.finally(() => {
setIsLoading(false)
})
}
fetchData()
}, [api, method, url, data, config])
return { response, error, isLoading }
}
and here is my component where I make fetch request via useFetch.
const { response, isLoading, error } = useFetch({
api: BaseURL,
method: 'get',
url: 'some',
})
everything works well request is works.
But when I try to pass to my some child component (child component wait string value) some string value from response.
here is the child component in the component where I make a fetch request.
return (
<Title>{response && response.id}</Title>
)
here is the title component
type Props = {
children: string
}
export const Title: FC<Props> = ({ children }) => {
return <h4>{children}</h4>
}
I get this error:
Type 'null' is not assignable to type 'string | (string & {}) | (string & ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)>) | (string & ReactNodeArray) | (string & ReactPortal)'.ts(2322)
Object is possibly 'null'.ts(2531)
It's the first question of how I can implement this hook in a typescript way.
And here using fetch API. How I can use here Axios?
question from:
https://stackoverflow.com/questions/65651772/usefetch-hook-with-typescript-and-axios