Question:
How do I conditionally return function in javascript?

One way to make the hook work for both use cases by returning a function with properties attached to it. Something like:


function useMyHook() {

  const MyCTX = useContext(MyContext);

  if (!MyCTX) {

    throw new Error("useMyHook must be defined.");

  }


  // Create a function that calls MyCTX.show

  const callableFunction = function() {

    return MyCTX.show();

  };


  // Attach show and hide properties to the function

  callableFunction.show = MyCTX.show;

  callableFunction.hide = MyCTX.hide;


  return callableFunction;

}


// Usage 

// Either

const { show, hide } = useMyHook();

// Or

const show = useMyHook();


Alternative Approach

Another way would require you to use a parameter(if you like to change the signature of your hook) to your hook based on which you can conditionally use them. A sample would look like:


const useMyHook = (returnObject = false) => {

  const MyCTX = useContext(MyContext);

  if (!MyCTX) {

    throw new Error('useMyHook must be defined.');

  }

  // Conditionally return based on the `returnObject` parameter

  if (returnObject) {

    return {show: MyCTX.show, hide: MyCTX.hide};

  } else {

    return MyCTX.show;

  }

};


// To use


// Just get the `show` function

const show = useMyHook();


// Get both `show` and `hide` functions in an object

const {show, hide} = useMyHook(true);


Note:

  1. You can also leverage Proxy API to achieve your requirement. Although, there might be some performance bottleneck to it(in case you're ready to sacrifice some) since it intercepts and redefines operations on objects.

  2. If there is not a very specific need I would stick to the destructure approach and leave it on devs(using the hook) as what they want to destructure from the hook.



Suggested blogs:

>How to do light and dark mode in a website using HTML and JavaScript?

>How to fix mouseover event glitch in JavaScript?

>How to use querySelectorAll()" with multiple conditions in JavaScript?

>Fix ASP.NET Core Model Binding Not Working issue.

>How to create a zip file and return it to client for download?

>How to Group large number of data based on CreatedDate(DateTime)?

>Issues converting ASPX Web app from .net 3.5 to 4.8.1

>Fix Asp.net issue: AjaxControlToolkit FileUpload not working

>Using Fetch in JS to call a server-side method (ASP.NET)



Ritu Singh

Ritu Singh

Submit
0 Answers