I want to fetch some data from an API and then use it everywhere, even outside the component. To be more specific, I managed to fetch some data through an API and are able to do some manipulation about it in the component where I did the call to fetch, but how can I still get access to those fetched data when I am in another component?
In Tables.js I did the call to fetch from API and created a table for it.
import React, { useEffect, useState} from 'react';
const Tables = () => {
const [users, setUser] = useState([]);
useEffect(() => {
fetch(TEST_URL)
.then((res) => res.json())
.then((data) => {
setUser(data);
console.log(data)
});
}, []);
return (
<div>
<Table striped bordered hover>
<thead>
<tr>
<th>NAME</th>
<th>ADDRESS</th>
</tr>
</thead>
<tbody>
{users}.map((m) => (
<tr key={m.id}>
<td>{m.name}</td>
<td>{m.address}</td>
</tr>
))}
</tbody>
</Table>
</div>
);
}
export default Tables
And the data in the API looks like this:
[
{
"id": 1,
"name": "decster",
"address": "space",
"phone": "123"
}
]
Now I have another component called TableDetails.js, I would like to use the data from the API without re-fetching it, and create a table rendering a different part of that data, for example: displaying "name" and "phone" from the JSON data this time. How should I do it?
import Tables from "./Tables.js";
function TableDetails() {
return (
<div>
<h2>
<Tables Tables {users} = {columns}>
</h2>
</div>
)
}
export default TableDetails
Another small issue I have is that after fetching the data in Tables.js, it repeatedly print the data in the console log twice? I am very nice to REACT and also JS, so any tips would be very helpful! Thanks