I'm trying to write a custom hook useFetch that makes many requests for different data.
The problem is that I can't typing my date correctly, I have state like this.
interface IState<T> {
data: T | T[]
loading: boolean,
error: boolean,
}
Initial state
const initialState = {
data: [],
loading: false,
error: false,
}
useEffect
useEffect(() => {
setData((prevState) => ({...prevState, loading: true}));
axios.get(url)
.then(response => response.data.results ? response.data.results as T[] : response.data as T)
.then((data) => (setData((prevState) => ({...prevState, loading: false, data}))))
.catch(e => {
setData((prevState) => ({...prevState, error: true}));
if (e instanceof Error) console.log(e.message);
})
}, []);
When i get response.data.results i have array of objects and when i have response.data i have only one object. I'm trying to return the right type.
I call my function like this useFetch and I have result like this MovieType | MovieType[]. I don't need TypeGuard I need only one correct type.
If you see any problems please let me know.
Thanks a lot!