0
votes

On page load I need to perform some logic based on the URL and then dispatch a Redux action. This code works fine but gives me a TypeScript error:

React.useEffect(() => {

const { search } = window.location;
const removeFirstQuestionMark = search.slice(1);

if (!removeFirstQuestionMark) {
  return null;
}

// more logic 

reduxAction({
  foo: 'bar'
});
  return null;
}, []);

error TS2345: Argument of type '() => null | undefined' is not assignable to parameter of type 'EffectCallback'. Type 'null | undefined' is not assignable to type 'void | (() => void | undefined)'. Type 'null' is not assignable to type 'void | (() => void | undefined)'.

14 React.useEffect(() => {

2

2 Answers

0
votes

useEffect return value should be a callback which allows to do things on component did mount

React.useEffect(() => {
  const { search } = window.location;
  const removeFirstQuestionMark = search.slice(1);

  if (!removeFirstQuestionMark) {
    return null; // do not return but you can use if else to avoid next code execution
  }

  // more logic

  reduxAction({
    foo: "bar"
  });
  return () => {
    // Things to do on component will unmount
  };
}, []);
0
votes

Inside the useEffect we generally return a function that does some cleanup work when the component unmounts. If you don't want to do anything like that then don't return anything.

React.useEffect(() => {

const { search } = window.location;
const removeFirstQuestionMark = search.slice(1);

if (!removeFirstQuestionMark) {
  return null;
}

// more logic 

reduxAction({
  foo: 'bar'
});
//  return null;
}, []);