I'm doing a tutorial on React Hooks and fetching data. Here's my component to fetch customers and map them out in a list:
const useFetch = (url: string) => {
const [customers, setCustomers] = useState<null | []>(null);
const [loading, setLoading] = useState(true);
// Similiar to componentDidMount() and componentDidUpdate()
useEffect(() => {
const fetchData = async () => {
const result = await axios(url);
setCustomers(result.data);
setLoading(false);
};
fetchData();
});
return { customers, loading };
};
const url = 'https://jsonplaceholder.typicode.com/users';
export const LatestCustomers: React.FC<Props> = ({
description
}: Props): JSX.Element => {
const { customers, loading } = useFetch(url);
return (
<Container>
{loading ? (
<div>...Loading...</div>
) : (
<tr>
{customers.map(customer => (
<div key="user.id">{customer.name}</div>
))}
</tr>
)}
</Container>
);
};
With that, I got the error:
Object is possibly 'null'. TS2531
108 | ) : (
109 | <tr>
> 110 | {customers.map(customer => (
| ^
111 | <div key="user.id">{customer.name}</div>
112 | ))}
113 | </tr>
How do I solve this?
const { customers = [], loading } = useFetch(url);will solvenull.mapis aTypeError).