I am not able to use useHistory function in action creator file

Viewed 508

I am using react-router-dom and and redux. I use history.push("/") after dispatching but it shows error. I want user to navigate to "/" after successfull authentication(USING GOOGLE)

    export const googleLogin = () => async (dispatch) => {
  try {
    const response = await auth.signInWithPopup(provider);
    const doc = await db.collection("users").doc(response.user.uid).get();

    if (doc.exists) {
      await db
        .collection("users")
        .doc(response.user.uid)
        .set(
          {
            accountDetail: {
              emailVerified: response.user.emailVerified,
              photoURL: response.user.photoURL,
            },
          },
          { merge: true }
        );
history.push("/")
    } else {
      await db
        .collection("users")
        .doc(response.user.uid)
        .set({
          accountDetail: {
            userId: response.user.uid,
            displayName: response.user.displayName,
            email: response.user.email,
            photoURL: auth.currentUser.photoURL,
            accountCreatedAt: Date.now(),
          },
        });
history.push("/")
    }
      } catch (error) {
        await dispatch({ type: AUTH_ERROR, payload: error.message });
      }
    };
1 Answers

You can not use useHistory hook in your action creator file because it is neither a React function component nor a custom hook.

As per rules of hooks, a React Hook, e.g. useHistory, can only be used in a function component or in a custom hook.

But, if you want to access history object outside a React component, you can create your own history object and provide it to Router (from react-router-dom) as shown below:

Create a file, history.js:

import { createBrowserHistory } from 'history'

export default createBrowserHistory()

Use Router and provide it your history object:

import history from '../path/to/history'
import { Router } from 'react-router-dom'

// ...

return (
  <Router history={history}>
    <App/>
  </Router>
)

Now, you can easily import and use history in action creator file.

Any js file:

import history from '../path/to/history'

// ...

history.push("/some/path")

Related: Why is 'history' necessary in the Router of React-Router-Dom?


Note: Using Router doesn't stop you from using useHistory hook or withRouter HOC as you would normally use i.e. you can still use the hook or HOC in other React components to get the history.

Related