Как связать перехватчики ax ios с избыточным хранилищем в приложении Next. js? - PullRequest
1 голос
/ 22 февраля 2020

Я создаю службу API следующим образом:

export default class ApiService {
    static init(store) {
        axios.interceptors.request.use(config => {
            const { token } = store.getState().user;

            config.baseURL = ${process.env.NEXT_STATIC_API_URL};

            if (token) {
                config.headers.Authorization = Bearer ${token};
            }

            return config;
        });
    }
}

И запускаю ее здесь в главном компоненте приложения:

class EnhancedApp extends App {
    static async getInitialProps({ Component, ctx }) {
        let pageProps = {};
        const { store } = ctx;

        if (!isClient()) ApiService.init(store);

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(ctx);
        }

        return { pageProps };
    }

    componentDidMount() {
        ApiService.init(this.props.store);
    }

    render() {
        const { Component, pageProps, store } = this.props;

        return (
            <Provider store={store}>
                <Component {...pageProps} />
            </Provider>
        );
    }
}

export default withRedux(configureStore, { debug: true })(
    withReduxSaga(EnhancedApp)
);

Я использую оболочку для получения пользовательских данных для каждая страница:

const checkAuth = async (ctx, isProtected) => {
    const { auth } = nextCookie(ctx);

    if (isProtected && !auth) {
        if (!isClient() && ctx.res) {
            ctx.res.writeHead(302, { Location: '/' });
            ctx.res.end();
        } else {
            await Router.push('/');
        }
    }

    return auth || null;
};

export const withAuth = (isProtected = false) => (WrappedComponent) => {
    const WrappedWithAuth = (props) => {
        const { token } = useSelector(
            state => state.user
        );

        useEffect(() => {
            if (isProtected && !token) Router.push('/');
        }, [token]);

        return <WrappedComponent {...props} />;
    };

    WrappedWithAuth.getInitialProps = async (ctx) => {
        const token = await checkAuth(ctx, isProtected);
        const { store } = ctx;

        if (token) {
            store.dispatch(userSetToken(token));

            try {
                const { data } = await UserService.getProfile();
                store.dispatch(userGetProfileSuccess(data));
            } catch (e) {
                store.dispatch(userGetProfileFailure(e));
            }
        }

        const componentProps =
            WrappedComponent.getInitialProps &&
            (await WrappedComponent.getInitialProps({ ...ctx, token }));

        return { ...componentProps };
    };

    return WrappedWithAuth;
};

На клиентской стороне все работает правильно, но когда я меняю пользователя и ссылаюсь на sh, я вижу страницу, на которой вызов API get profile на стороне сервера продолжает использовать предыдущий токен.

...