Like the title says useFetch custom hook that I made is returning data twice, what do I mean by that. Well when I console.log the data that I fetched there are two outputs, one of them has value null, and the other is the data that I want, and because there is data with null value, that is a problem since I can't fulfill the table with the data I want. Here is the code:
import { useState, useEffect } from "react";
import axios from "axios";
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
axios
.get(url)
.then((response) => {
setData(response.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setLoading(false);
});
}, [url]);
return { data, loading, error };
};
export default useFetch;
And this is where I want to use the data I fetched:
import React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import useFetch from "./custom_hooks/useFetch";
const TableComponent = () => {
const { data, loading, error } = useFetch(
"https://gorest.co.in/public/v1/users?page=1"
);
if (loading) return <h1> LOADING...</h1>;
if (error) console.log(error);
console.log(data);
return (
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell>User Names</TableCell>
<TableCell align="right">Email</TableCell>
<TableCell align="right">Status</TableCell>
<TableCell align="right">Gender</TableCell>
<TableCell align="right">ID</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.data.map((user) => {
return (
<TableRow>
<TableCell>{user.name}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
);
};
export default TableComponent;
When I refresh the page, there is an error 'Data is null', how to fix this?