With this code:
const Products = () => {
const classes = useStyles();
const { data } = useFetch('/categories');
return (
<div className={classes.root}>
<GridList cellHeight={180} className={classes.gridList}>
<GridListTile key="Subheader" cols={6} style={{ height: 'auto' }} />
{data &&
data.map((category: CategoryInterface) => {
return (
<GridListTile key={category.id}>
<GridListTileBar title={category.name} />
</GridListTile>
);
})}
</GridList>
</div>
);
};
I get 'Object is possibly null' on data before the map, I tried using the && operator to get rid of it and I also tried defining a variable like const categories = data as CategoryInterface[]
but that showed me I had to convert to unknown first, how should I do this instead?
Here is the useFetch hook
import { useEffect, useState } from 'react';
export const useFetch = (url: string) => {
const [state, setState] = useState({ data: null, loading: true });
useEffect(() => {
setState(state => ({ data: state.data, loading: true }));
fetch(url)
.then(res => res.json())
.then(json => setState({ data: json, loading: false }));
}, [url, setState]);
return state;
};