Skip to content
Open

Hw5 #28

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import firebase from 'firebase'

export const appName = 'advreact-1610'
export const appName = 'advreact-1610-kys'

firebase.initializeApp({
apiKey: "AIzaSyB31xpTtp4Jln_hb2kAbE4PGf6Mi8EgLyA",
apiKey: "AIzaSyCuzZg-9QjuEEIHNSmJEL4VaAb3QtKb4xQ",
authDomain: `${appName}.firebaseapp.com`,
databaseURL: `https://${appName}.firebaseio.com`,
projectId: appName,
storageBucket: "",
messagingSenderId: "397157634637"
messagingSenderId: "437473203897"
})
37 changes: 25 additions & 12 deletions src/ducks/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {appName} from '../config'
import {Record} from 'immutable'
import firebase from 'firebase'
import {createSelector} from 'reselect'
import {call, put, all, take} from 'redux-saga/effects'
import {call, put, all, take, spawn} from 'redux-saga/effects'
import {eventChannel} from 'redux-saga'
import {replace} from 'react-router-redux'

/**
Expand Down Expand Up @@ -69,15 +70,6 @@ export function signIn(email, password) {
}
}

firebase.auth().onAuthStateChanged(user => {
if (!user) return

window.store.dispatch({
type: SIGN_IN_SUCCESS,
payload: { user }
})
})

/**
* Sagas
**/
Expand Down Expand Up @@ -126,11 +118,32 @@ export const signInSaga = function * () {
}
}

const createAuthSocket = () => eventChannel(emit => {
const callback = user => emit({ user })

let unsubscribe = firebase.auth().onAuthStateChanged(callback)

return unsubscribe
})

export function * watchStatusChangeSaga() {

const chan = yield call(createAuthSocket)

while (true) {
yield take(SIGN_IN_SUCCESS)

yield (put(replace('/admin')))
const { user } = yield take(chan)

if(user){

yield put({
type: SIGN_IN_SUCCESS,
payload: { user }
})

yield (put(replace('/people')))

}
}
}

Expand Down
53 changes: 45 additions & 8 deletions src/ducks/people.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,24 +177,61 @@ const createPeopleSocket = () => eventChannel(emit => {

ref.on('value', callback)

return () => ref.off('value', callback)
return () => {console.log('YA-HA_HA');ref.off('value', callback)}
})

export const cancelableRealtimePeopleSyncSaga = function * () {
let task
while (true) {
const {payload} = yield take('@@router/LOCATION_CHANGE')
console.log('---payload cancelableRealtimePeopleSyncSaga: ', payload);

if (payload && payload.pathname.includes('people')) {
task = yield fork(realtimePeopleSyncSaga)

} else if (task) {
yield cancel(task)
}
}
}

export const realtimePeopleSyncSaga = function * () {
const chan = yield call(createPeopleSocket)

while (true) {
const { data } = yield take(chan)
try{
while (true) {


yield put({
type: FETCH_ALL_SUCCESS,
payload: data.val()
})
/* Вопрос:
* Не понимаю, почему следующие две строчки срабатывают только один раз
* если yield spawn(realtimePeopleSyncSaga)
* */
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну ты ведь каждый раз ждешь изменения роута

Copy link
Author

@karalkou karalkou Nov 13, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

смотри, у меня есть сага realtimePeopleSyncSaga.
Внутри неё я хочу ловить событие смены урла, и использовать возвращаемое yield-ом значение payload:

export const realtimePeopleSyncSaga = function * () {
    const chan = yield call(createPeopleSocket)
        while (true) {
            
            /* вот тут хочу получать данные и реагировать на них */
            const {payload} = yield take(LOCATION_CHANGE)
            console.log('---payload: ', payload);

        }
}

И я её вызываю в главной саге утки:

export function * saga() {
    yield spawn(realtimePeopleSyncSaga)
    // yield spawn(cancelableRealtimePeopleSyncSaga)

    yield all([
        takeEvery(ADD_PERSON_REQUEST, addPersonSaga),
        takeEvery(ADD_EVENT_REQUEST, addEventToPersonSaga)
    ])
}

По идее, теперь при каждом переходе (на админа или события, должно происходить событие смены урла и выводится payload). Событие происходит, но не отрабатывает console!

И вот это я не понимаю.

Задание сделал: через создание ещё одной саги cancelableRealtimeSyncSaga, которую отменяю и в отмененной саге (realtimePeopleSyncSaga) уже отключаю канал в finally.

Но первая мысль была сразу обрабатывать смену урла в realtimePeopleSyncSaga и отключать канал.
И не пойму, почему именно она не работает. Событие смены происходит, а реакции ноль

const {payload} = yield take('@@router/LOCATION_CHANGE')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше использовать {LOCATION_CHANGE} from 'react-router-redux'

console.log('---payload: ', payload);



const { data } = yield take(chan)

yield put({
type: FETCH_ALL_SUCCESS,
payload: data.val()
})
}
} finally {
if (yield cancelled()) {
console.log('---start to cancel');
yield call([chan, chan.close])
console.log('---finish to cancel');

}
}

}

export function * saga() {
yield spawn(realtimePeopleSyncSaga)
// yield spawn(realtimePeopleSyncSaga)
yield spawn(cancelableRealtimePeopleSyncSaga)

yield all([
takeEvery(ADD_PERSON_REQUEST, addPersonSaga),
Expand Down