I want to create a copy of an array from an api to avoid using "data?.map", in order to be able to sort it later in a table.
my use fetch hook:
import { useEffect, useState } from "react";
import axios from "axios";
import { BASE_URL } from "../constants/Constants";
const useFetchData = (url: string) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
const options = {
method: "GET",
url: `${BASE_URL}${url}`,
};
axios
.request(options)
.then((response) => {
setData(response.data);
})
.catch((error) => {
setError(error);
console.error(error);
})
.finally(() => {
setLoading(false);
});
}, [url]);
return { data, loading, error };
};
export default useFetchData;
my Table component:
const { data, loading, error } = useFetchData(SPOT_URL);
const [searchTerm, setSearchTerm] = useState("");
// Table data that displays all the entries or the ones that have the value of the name or
// country inside the SearchInput component
const tableData = data?.filter(
(val: { country: string; name: string }) =>
(searchTerm === "" && val) ||
(val.country.toLowerCase().includes(searchTerm.toLowerCase()) && val) ||
(val.name.toLowerCase().includes(searchTerm.toLowerCase()) && val)
);
…
// After the tableData function is complete, the table rows are generated
const dashboardTableContent = tableData?.map(
(item:) => (
<tr key={item.id}>
<td>{item.name}</td>
<td>{item.country}</td>
<td>{item.lat}</td>
<td>{item.long}</td>
<td>{item.probability}%</td>
<td>{item.month}</td>
</tr>
)
);
…
return (<tbody>{dashboardTableContent}</tbody>)
Is there a way to avoid using the question mark and start using just "data" ?
What I am trying to do is a sortable table ascending descending like in this link https://www.smashingmagazine.com/2020/03/sortable-tables-react/
In this link is a spread operator, which I can’t use in my code because I don’t have the array in the begging and it renders a white page.
>Solution :
If all you want is to avoid the question mark, you can just do
const [data, setData] = useState([]);
Instead of
const [data, setData] = useState(null);
You will get an empty array from the start