Я создаю компонент высшего порядка withAuth
для проверки подлинности некоторых страниц в моем приложении. Он работает, проверяя хранилище Redux на currentUser
, и, если его там нет, попытается извлечь текущего пользователя. API использует сессии на основе cook ie, поэтому для аутентификации пользователя данные запроса не требуются. Вот функция аутентификации:
// actions/authActions.ts
const dispatchCurrentUser = () => dispatch => {
return axios.get('localhost:8000/api/user').then(res => {
return dispatch({ type: 'GET_CURRENT_USER', payload: res.data })
}
}
Вот как выглядит мой HO C
// hocs/withAuth.tsx
import cookies from 'js-cookie'
import { NextPageContext } from 'next'
import React from 'react'
import { connect } from 'react-redux'
import { dispatchCurrentUser } from '../actions/authActions'
import { RootState } from '../store'
import { IUser } from '../types/auth'
import redirect from '../utils/redirect'
const withAuth = <T extends object>(C: React.ComponentType<T>) => {
const AuthComponent = (props: any) => {
return (
<C {...props} />
)
}
AuthComponent.getInitialProps = async (context: NextPageContext) => {
const { store, isServer } = context
const state: RootState = store.getState()
const currentUser: IUser = state.auth.user
if (!currentUser) {
store.dispatch(dispatchCurrentUser()).then(() => null, (error: any) => {
console.log('User is not authenticated.')
// Here, user is redirected.
})
}
return { isServer }
}
return connect((state: RootState) => state.auth.user, {dispatchCurrentUser})(AuthComponent)
}
export default withAuth
Я получаю ошибку на store.dispatch
, которая говорит "Argument of type '(dispatch: any) => Promise<any>' is not assignable to parameter of type 'AnyAction'."
Это заставляет меня поверить, что промежуточное ПО react-thunk
не берется, но я не уверен. Вот как выглядит моя makeStore
функция:
// store.ts
import { MakeStore } from 'next-redux-wrapper'
import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import { rootReducer } from './reducers'
export type RootState = ReturnType<typeof rootReducer>
const makeStore: MakeStore = (initialState: any = {}) => {
return createStore(
rootReducer,
applyMiddleware(thunk)
)
}
export default makeStore
Любая помощь будет принята с благодарностью!