rel1x rel1x - 3 months ago 28
React JSX Question

What's wrong with my redux-saga

I create a React Native app. My

index.ios.js
where I add middlewares to the store.

import React, { Component } from 'react'
import {
AppRegistry,
} from 'react-native'
import { Provider } from 'react-redux'
import { applyMiddleware, createStore } from 'redux'
import createLogger from 'redux-logger'
import createSagaMiddleware from 'redux-saga'

import reducer from './src/reducers'
import * as sagas from './src/sagas'
import Scene from './src/components/scene'

const store = createStore(
reducer,
applyMiddleware(createSagaMiddleware(...sagas), createLogger())
);

const CitiesApp = () => (
<Provider store={store}>
<Scene />
</Provider>
);

AppRegistry.registerComponent('CitiesApp', () => CitiesApp);


I have an action:

export const USER_FETCH_REQUESTED = 'USER_FETCH_REQUESTED';
export const fetchUser = () => ({
type: USER_FETCH_REQUESTED
});


Which I call from
componentDidMount
in a component

componentDidMount() {
this.props.dispatch(fetchUser());
console.log('componentDidMount')
}


Also I have a saga:

export function* watchUserFetch() {
console.log('watchUserFetch');
yield take(actions.USER_FETCH_REQUESTED);
yield fork(fetchUser);
}

function* fetchUser() {
try {
const user = yield call(() => Api.fetchUser());
yield put({type: actions.USER_FETCH_SUCCEEDED, user});
} catch (e) {
yield put({type: actions.USER_FETCH_FAILED, message: e.message});
}
}


But the saga doesn't work. I don't saw
watchUserFetch
in console and
fetchUser
function doesn't run.

Where is my mistake? Why
fetchUser
doesn't run?

Answer
  1. create root saga

    export default function* rootSaga() {
        yield [
            watchUserFetch()
        ]
    }
    
  2. then run rootSaga

    import createSagaMiddleware from 'redux-saga';
    import rootSaga  from './sagas.js';
    
    const sagaMiddle= createSagaMiddleware();
    
    const store = createStore(reducer,
        applyMiddleware(sagaMiddle,createLogger())
    );
    
    sagaMiddle.run(rootSaga);
    

webpackbin example