i've written a custom hook to help me not repeat code for some fetch calls. it looks like this:
export const useCustomQuery = ({ endpoint, body, dataPoint }: args) => {
const [data, setData] = useState()
useEffect(() => {
fetch(`http://localhost:4000/${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
})
.then((res) => res.json())
.then((res) => {
if (dataPoint) {
setData(JSON.parse(res.data[dataPoint]))
}
})
}, [endpoint, body, dataPoint])
return { data }
}
but I'm getting some TS errors complaining about the type of data. is it possible to pass in the type as an argument as it might be different for each component that calls the hook? or what is the best way to approach this?
You can use generic in this case. You can do something like this:
export const useCustomQuery = <T,>({ endpoint, body, dataPoint }: args) => {
const [data, setData] = useState<T>()
...
}
This way, you are giving a type T when you call the hook useCustomQuery, that parameterized the type of data, like this:
useCustomQuery<MyType>({...})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With