PatrickDD PatrickDD - 1 month ago 28
React JSX Question

Displaying HTTP Request Reponse With Redux Saga

Heyy so I want to get a json from a request with react-saga! I was wondering how I would get the data that the my saga yields, I have an idea to call a generator function in the componentWillMount that watches for the 'REQUEST_DONE' action with takeLatest and then rerenders.

But I think it would a bad idea to use react-saga in one of my components. Guidance please

My saga file:

export function* Saga() {
yield fetch(url, {
method: 'GET',
headers: {
'Accept': '...',
'Content-Type': 'application/json'
}
})
.then(response => {
return response.json();
})
.then(json => {
return json;
})
.catch(ex => {
console.log('parsing failed', ex)
})
}

export default function* watchAsync() {
console.log(yield Saga().next().value); // gets the value correctly
yield* takeLatest('BLAH', Saga);
}


My component

...
componentWillMount() {
const { store } = this.context;
store.dispatch({type: 'BLAH'});
// I want the request data
}

render() { ... }

Answer

EDIT webpackbin DEMO

call fetch and yield result

import { take, put, call } from 'redux-saga/effects';

function fetchData() {
    return  fetch(url)
    .then(res => res.json() )
    .then(data => ({ data }) )
    .catch(ex => {
        console.log('parsing failed', ex);
        return ({ ex });
    });
}

function* yourSaga(action) {
    const { data, ex } = yield call(fetchData);
    if (data)
    yield put({ type: 'REQUEST_DONE', data });
    else
    yield put({ type: 'REQUEST_FAILED', ex });
}
export default function* watchAsync() {
    yield* takeLatest('BLAH', yourSaga);
}

then connect component and slice needed data

class App extends Component {
    ...
    componentWillMount() {
        this.props.dispatch({type: 'BLAH'});
    }

    render(){
        return (<div>Data: {this.props.data}</div>);
    }
}

export default connect( state =>({
    data:state.data
}))(App);
Comments