Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Saga in Component
import React from 'react'
import CommentList from './CommentList'
import api from '../../lib/api'
import { bindActionCreators } from 'redux'
import TechReactor from '../shared/TechReactor'
const statusPrefix = 'IssueCommentContainer'
// Action types
const REQUEST_COMMENT_CREATE = `${statusPrefix}/REQUEST_COMMENT_CREATE`
const SUCCESS_COMMENT_CREATE = `${statusPrefix}/SUCCESS_COMMENT_CREATE`
const FAILURE_COMMENT_CREATE = `${statusPrefix}/FAILURE_COMMENT_CREATE`
// Status ENUM
const IDLE = `${statusPrefix}/IDLE`
const WORKING = `${statusPrefix}/WORKING`
const ERROR = `${statusPrefix}/ERROR`
// Test callee
const test = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({message: 'some data'})
}, 2000)
})
}
// Action creators
const actions = {
requestCommentCreate: () => ({
type: REQUEST_COMMENT_CREATE
}),
successCommentCreate: (data) => ({
type: SUCCESS_COMMENT_CREATE,
payload: data
})
}
const mySaga = function * () {
while (true) {
yield * this.take(REQUEST_COMMENT_CREATE)
console.log('taken')
try {
const data = yield * this.call(test)
console.log('called', data)
yield this.put(actions.successCommentCreate(data))
continue
} catch (error) {
console.log(error)
}
}
}
const myReducer = (state, action) => {
switch (action.type) {
}
return state
}
class IssueCommentContainer extends TechReactor {
constructor (props) {
super(props)
this.state = {
comments: props.comments,
status: IDLE
}
}
actions = bindActionCreators(actions, ::this.dispatch)
reducer = myReducer
saga = mySaga.call(this)
render () {
const {
user,
issue
} = this.props
return <CommentList
user={user}
comments={issue.comments}
actions={this.actions}
/>
}
}
export default IssueCommentContainer
import React from 'react'
class TechReactor extends React.PureComponent {
componentWillMount () {
this.saga.next()
}
* saga () {
while (true) {
console.warn('Define saga method!!')
yield
}
}
* take (targetAction) {
while (true) {
const action = yield
if (action.type === targetAction) {
break
}
console.log('reject')
}
}
* call (callee, ...args) {
let resolved = false
let result
Promise.resolve(callee(...args))
.then(data => {
resolved = true
result = data
this.saga.next()
})
while (true) {
yield
if (resolved) break
}
return result
}
dispatch (action) {
this.saga.next(action)
const newState = this.reducer(this.state, action)
if (this.state !== newState) {
this.setState(newState)
}
}
reducer (state, action) {
console.warn('Define reducer!!')
return state
}
put (action) {
setImmediate(() => {
this.dispatch(action)
})
}
}
export default TechReactor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.