EN VI

Javascript - Getting an error if arrow function returns a function but not when it returns null for useEffect?

2024-03-11 21:30:04
Javascript - Getting an error if arrow function returns a function but not when it returns null for useEffect

This is a code snippet from my Articles component:

const [articles, setArticles] = useState([]);
  const [err, setErr] = useState("");

  const token = sessionStorage.getItem("token");
  const axiosWithToken = axios.create({
    headers: { Authorization: `Bearer ${token}` },
  });

  const getArticles = async () => {
    const res = await axiosWithToken.get("http://localhost:5000/user/articles");

    if (res.data.message === "All Articles") {
      setArticles(res.data.payload);
    } else {
      setErr(res.data.message);
    }
  };

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

This code is running without any errors. But I thought that using an arrow function with braces is too much just to run one function, so I changed the arrow function in the useEffect hook to this:

useEffect(() => getArticles(), []);

But now when I load the articles component and go to any other route the page throws an unknown error which just states that 'n' is not a function. I don't understand why this is happening, as I see it both of them are functionally the same thing.

Solution:

The problem is that by changing to the shorthand form, you've implicitly added a return. Your shorthand version isn't the same as your version with {}; instead, it's equivalent to this:

useEffect(() => {
    return getArticles();
//  ^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
}, []);

useEffect expects that if the callback you give it returns anything other than undefined, it's a cleanup function that React should use on unmount or prior to re-running the effect. (It doesn't check if the return value is a function, the test is literally !== undefined; see just after the // Unmount comment in commitHookEffectListUnmount.) From the documentation (my emphasis):

setup - The function with your Effect’s logic. Your setup function may also optionally return a cleanup function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function.

Your getArticles function returns a promise (like all async functions do), which React is trying to use as a cleanup function because it is !== undefined.

So you'll probably want to keep those {} rather than removing them. (There are other ways to avoid having the return value, but none of them is shorter than the {}.)

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login