How to use custom component multiple times in same component

Viewed 766

Basically i've created one custom component for api calling

import React, {useState, useEffect} from 'react';
import axios from 'axios';

export const useFetch = config => {
  const [Response, setResponse] = useState({});
  const [Error, setError] = useState({});
  const [ShowModal, setShowModal] = useState(false);
  const [ShowLoader, setShowLoader] = useState(false);

  useEffect(() => {
    callAPI();
  }, []);

  const callAPI = () => {
    setShowLoader(true);
    axios(config)
      .then(res => {
        console.log('==>>', res);
        if (res.status == 200) {
          setShowLoader(false);
          setResponse(res.data);
        }
      })
      .catch(err => {
        console.log('==>>', err.response);
        setError(err.response.data);
        setShowLoader(false);
        setShowModalErrorMessage(err.response.data.error);
        setShowModal(true);
      });
  };

  return {Response, Error, ShowModal, ShowLoader};
};

with the help on this i can call api and get response if i use it with useEffect/componentDidMount in component. But how to use same for calling different api on Button click. is it possible?

i followed this=> post

2 Answers

Add setUrl method (can expand to setConfig) in useFetch. Here working demo for this in stackblitz

import React, {useState, useEffect} from 'react';
import axios from 'axios';

const useFetch = ({}) => {
  const [Response, setResponse] = useState({});
  const [Error, setError] = useState({});
  const [ShowModal, setShowModal] = useState(false);
  const [ShowLoader, setShowLoader] = useState(false);
  const [url, setUrl] = useState("");

  useEffect(() => {
    if (url) {
      console.log('making request ', url);
      callAPI();
    }
  }, [url]);

  const callAPI = () => {
    setShowLoader(true);
    axios(url)
      .then(res => {
        console.log('==>>', res);
        if (res.status == 200) {
          setShowLoader(false);
          setResponse(res.data);
        }
      })
      .catch(err => {
        console.log('==>>', err.response);
        setError(err.response.data);
        setShowLoader(false);
        setShowModalErrorMessage(err.response.data.error);
        setShowModal(true);
      });
  };

  return {Response, Error, ShowModal, ShowLoader, setUrl};
};

export default useFetch;

On the button click, set url (expand to config)

import React, {useState, useEffect} from 'react';
import useFetch from './use-fetch';

export default ({ name }) => {
  const {Response, Error, ShowModal, ShowLoader, setUrl } = useFetch({});


 return (<div>
  <button key={'1'} onClick={() => setUrl("http://foo/items")}> Request 1 </button>
  <button key={'2'} onClick={() => setUrl("http://foo/other")}> Request 2 </button>
 </div>)

};

Common Request.js file using the fetch method

Request("POST","http://localhost/users/user",{'name':"",'add':""})

export default function Request(reqMethod, endPointUrl, bodyData) {   
 if (reqMethod === "POST") {
     return fetch(endPointUrl, {
        method: reqMethod,
        body: JSON.stringify(bodyData),
      })
  .then((response) => {
    return response.json();
  })
  .catch(() => {
    localStorage.clear();
  });
 } else if (reqMethod === "GET") {
    return fetch(endPointUrl, {
    method: reqMethod,
    })
  .then((response) => {
    return response.json();
  }).catch(() => {
    localStorage.clear();
  });
 }
}
Related