Sohaib Butt
Sohaib Butt

Reputation: 107

On dispatch it is showing me Uncaught RangeError: Maximum call stack size exceeded

I'm dispatching an logout action from Navbar component but it showing me maximum call stack size exceeded whenever i click on logout button.

authSlice.js:

export const logout = createAsyncThunk("logout", async (action) => {
  localStorage.clear();
  return action;
});

Navbar.js

  const logout = () => {
    dispatch(logout());
    setUser(null);
  };

Upvotes: 0

Views: 794

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42218

Infinite loop caused by ambiguous naming

You have two functions called logout!

const logout = () => {
    dispatch(logout()); // <-- calls itself
    setUser(null);
};

The second line here, logout(), is not calling your thunk action creator. It is calling the function on the first line. Which then executes the second line, which calls the first line, which executes the second line...until the Maximum call stack size is reached.


Make sure that you import the logout thunk into your component file.

import { logout } from '../some/thunk/file';

And rename your event handler to something else.

const handleLogout = () => {
    dispatch(logout()); // <-- calls the imported thunk
    setUser(null);
};

It's also possible to rename the thunk when you import it, if you want to do that instead.

import { logout as logoutAction } from '../some/thunk/file';
const logout = () => {
    dispatch(logoutAction()); // <-- calls the imported thunk
    setUser(null);
};

Upvotes: 2

Related Questions