Bishwas
Bishwas

Reputation: 203

How can I pass conditional value in custom Hook?

I have custom hook useFetch that takes URL as input and returns 3 data and I have Component CompanyListing to display those data. I want to send two different values as a URL in that hook using if else statement. If no search is done by user then display data from if endpoint, and if user search by keyword, then display from else endpoint. This is code that I wrote CompanyListing.js

const [counter, setCounter] = useState(1);
  let endpoint = `${CONSTANTS.BASE_URL}/companies?page=${counter}`;
  const searchCompanies = (searchTerm) => {
    if (searchTerm === '') {
      endpoint = `${CONSTANTS.BASE_URL}/companies?page=${counter}`;
      //console.log('DEFAULT ENDPOINT', endpoint);
    } else {
      endpoint = `${CONSTANTS.BASE_URL}/companies?search=${searchTerm}`;
      //console.log('SEARCH ENDPOINT', endpoint);
    }
  };
  //console.log('USEFETCH ENDPOINT', endpoint);
  const [companies, isLoading, meta] = useFetch(endpoint);
  return (
    <>
      <div data-testid="search-box">
        <SearchCompany callback={searchCompanies} />
      </div>
      {!isLoading ? (
        <div className="container">
          <div className="row" data-testid="company-list">
            {companies.length !== 0 && companies
              ? companies.map((company) => <CompanyLists key={company.id} {...company} data-testid="company-list" />)
              : 'No companies'}
          </div>
          <Pagination meta={meta} counter={counter} setCounter={setCounter} data-testid="paginate" />
        </div>
      ) : (
        <Spinner />
      )}
    </>
  );
};
export default CompanyListing;

When I tried calling useFetch inside if else, it goes against the rules of hooks and when I tried doing like in code above, I can't pass search endpoint to useFetch. Any idea how can I fix it? I tried by making all fetch on same component and it works perfectly but already having custom hook, I don't want to repeat code again. And any idea why I am getting 5 console for same thing ? Help will be much appreciated.

Upvotes: 1

Views: 722

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

Issue I think is that, your parent component is not being re-rendered when searchCompanies is called so as result useFetch won't get called, and also you can't use that inside the if else also,

So, I think you can do something like this, maintain the endpoint in state and change it when ever searchCompanies is being called, in that way your component will be re-rendered and you will get the latest endpoint.

const [counter, setCounter] = useState(1);
const [endpoint,setEndPoint] = useState(`${CONSTANTS.BASE_URL}/companies?page=${counter}`);

const searchCompanies = (searchTerm) => {
  if (searchTerm === '') {
    setEndPoint(`${CONSTANTS.BASE_URL}/companies?page=${counter}`);
  } else {
    setEndPoint(`${CONSTANTS.BASE_URL}/companies?search=${searchTerm}`);
  }
};

//console.log('USEFETCH ENDPOINT', endpoint);
const [companies, isLoading, meta] = useFetch(endpoint);

Upvotes: 1

Related Questions