@Miki8887
Front-end разработчик

Как правильно подключить centrifugo в React-Redux?

Кто-нибудь реализовывал подобное? Если да, то подскажите, как правильно настроить centrifugo в React-Redux. Она у меня в отдельном классе, запускается в componentWillMount. В action отправляю в канал сообщение, центрифуга его получает и должна выполниться функция из action на изменения состояния в store.
  • Вопрос задан
  • 1260 просмотров
Решения вопроса 1
@Miki8887 Автор вопроса
Front-end разработчик
Проблему решила. Извинюсь, что оперативно не разместила решение.
в main.js добавляются следующие строки:
import {Centrif} from './myCentrifugoClass.js'

ReactDOM.render(
    <Provider store={store}>
        <Router history={history}>
            <Switch>
                <Centrif>
                <Route path='/about' component={SPageController} />
                <Route path='/login' component={FormAuthController} />
                <Route path='/' component={requireAuthentication(basicLayoutController)} />
                </Centrif>
            </Switch>
        </Router>
    </Provider>,
  document.getElementById('content')
)


В файл reducers/actions.js:
require ('/js/json3.min.js')
import Centrifuge,{publish} from 'centrifuge'
var host = window.location.origin;
var timestamp = parseInt(new Date().getTime()/1000).toString();
var hmacBody = timestamp;
var secret = "ключ";
var shaObj = new jsSHA("SHA-256", "TEXT");
shaObj.setHMACKey(secret, "TEXT");
shaObj.update({"input":"hello"});
var token = shaObj.getHMAC("HEX");
import {subscription_namemod,centrifuge} from '/src/myCentrifugoClass.js'
//ну и уже в нужной вам функции добавляете к примеру
subscription_path.publish(data);


файл myCentrifugoClass.js:
import React from 'react'
import { connect } from 'react-redux'   // связывает хранилище Redux с компонентами React
import { bindActionCreators } from 'redux'
import { checkAuth,isAuthenticated,EAction,changePath,notAuthenticated } from './reducers/actions'
import { Redirect } from 'react-router-dom'
require ('/js/json3.min.js')
import Centrifuge from 'centrifuge'
var host = window.location.origin;
var timestamp = parseInt(new Date().getTime()/1000).toString();
var hmacBody = timestamp;
var secret = "пишем здесь ключ";
var shaObj = new jsSHA("SHA-256", "TEXT");
shaObj.setHMACKey(secret, "TEXT");
shaObj.update(hmacBody);
var token = shaObj.getHMAC("HEX");
var centrifuge = new Centrifuge({
    url: 'адрес где крутится центрифуга',
    user: "",
    timestamp: timestamp,
    token: token
});
var path; 
export var subscriptionb;
export var subscription_path;

class Appet extends React.Component {

    componentWillMount(){
        var df = this;

        if (path==null){
            path="/"
        }

        centrifuge.on('connect', function() {
            console.log('Центрифуга подключена');

            subscription_path = centrifuge.subscribe(path, function(message) {
                    console.log('message',message.data.action);
                switch (message.data.action){
                    case "isLogin":
                        df.props.isAuthenticated();
                    break;
                    case "isLogout":
                        df.props.notAuthenticated();
                        <Redirect to='/login'/>
                    break;
                }
            });

            subscriptionb = centrifuge.subscribe('work', function(message) {
                console.log('работает');
            });
        });
        centrifuge.connect();
    }

    componentDidUpdate(){
        path=this.props.location.pathname;
        console.log('Канал', path)
    }

    render() {
        return (
            <div>
                {this.props.children}
            </div>
        )
    }
}

export const Centrif = connect(state => ({state : state}),
            dispatch => bindActionCreators({isAuthenticated,changePath,notAuthenticated}, dispatch))(Appet)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы