skip to Main Content

On my API.js i have this code to call API JSON.

import { View, Text,Button, FlatList } from 'react-native';
import React, { useState } from 'react';
import axios from 'axios';

export default function APIs() {
  const [data, setData] = useState([]);
  const baseURL = 'https://jsonplaceholder.typicode.com';

  const getAPI = () => {
    axios({
      method: 'GET',
      url: `${baseURL}/posts`,
    })
    .then(res => console.log(res.data))
    .catch(err => console.log(err));

  };
}

How can I show response of that, on few pages?
Lets say on Home.js I want to display "id", then on title I want to display "title".
I mean, how can I make call and display it in the parts on multiple pages, each part on different page?

2

Answers


  1. Make it a hook:

    import {View, Text,Button, FlatList} from 'react-native';
    import React, {useState} from 'react';
    import axios from 'axios';
    
    export default function useApiHook({page}) {
      const [data, setData] = useState([]);
      const baseURL = 'https://jsonplaceholder.typicode.com';
    
      const getAPI = (location, controller) => {
        axios({
          method: 'GET',
          url: `${baseURL}/${location}`,
          signal: controller.signal,
        })
        .then(res => setData(res.data))
        .catch(err => console.log(err));
    
      };
    
      useEffect(() => {
         const controller = new AbortController();
         getApi(page, controller);
         
         return () => controller.abort();
      }, [page])
      
      return data;
    }
    

    Use in individual pages:

    const Home = () => {
      const response = useApiHook({page: 'id'});
      console.log(response);
    }
    
    const Title = () => {
      const response = useApiHook({page: 'title'});
      console.log(response);
    }
    

    react-doc

    Login or Signup to reply.
  2. If your <Home /> and <Title /> components have a common ancestor (<App /> in the snippet blow), then this component can fetch the data needed, store it, then send each required piece to the corresponding child component through props.

    The following snippet showcases a simple example where the <App /> component fetches the data, then sends the ID of the 1st element to <Home /> and the title to <Title />.

    const { useState, useEffect } = React;
    
    function Home(props) {
      return (
        <div>1st item ID: {props.firstItemID}</div>
      );
    }
    function Title(props) {
      return (
        <div>1st item title: {props.firstItemTitle}</div>
      );
    }
    function App() {
      const [posts, setPosts] = useState([]);
    
      useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/posts')
          .then(response => setPosts(response.data));
      }, []);
    
      return (
        <div>
          <Home firstItemID={(posts[0] || {}).id} />
          <Title firstItemTitle={(posts[0] || {}).title} />
        </div>
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js"></script>
    <div id="root" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search