简体   繁体   中英

Reuse data from API in another component | REACT

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

The fact that the console.log runs twice can be because of using the React.StrictMode wrapper in the root of the project (index.js) .

If you want the API to run somewhere and its data can be accessed in other components, you need a state manager like Redux Toolkit or in the simpler form, you can use useContext .

Here I write a solution for your problem using useContext .

Create a context called DataContext and in the App component, wrap all the content around it. (I am using jsonplaceholder fake data here)

export const DataContext = createContext();

function App() {
  const [data, setData] = useState([]);
  const callApi = () => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => setData(json));
  }
  return (
    <DataContext.Provider value={{data, callApi}}>
      <C1 />
      <C2 />
    </DataContext.Provider>
  );
}

Now callApi function and data value are accessible inside each child component. C1 calls getPosts API using callApi from context.

export default function C1() {
    const { callApi } = useContext(DataContext);
    useEffect(() => {
        callApi();
    }, [])
    return (
        <>This is C1 component. It calls the API.</>
    )
}

C2 can get API result from data value of the context.

export default function C2() {
    const { data } = useContext(DataContext);
    return (
        <>
            <div>
                This is C2 it gets API data from DataContext which has been called by C1
            </div>
            {
                data && data.map((post,index) => 
                    <p key={index}> { JSON.stringify(post) } </p>
                )
            }
        </>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM