Last active
April 22, 2019 18:00
-
-
Save turingmachine/cc5b572559f14b43c375cfa84daf3c83 to your computer and use it in GitHub Desktop.
React / MobX / socket.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SERVER: | |
io.on('connection', socket => { | |
socket.on('pickingstates.update', async pickingstateMsg => { | |
const [pickingstate, created] = await models.Pickingstates.findOrCreate( | |
{ | |
where: { | |
deliveryDate: pickingstateMsg.deliveryDate, | |
orderId: pickingstateMsg.orderId, | |
productId: pickingstateMsg.productId, | |
}, | |
} | |
) | |
await pickingstate.update({ | |
state: pickingstateMsg.state, | |
data: pickingstateMsg.data, | |
}) | |
socket.broadcast.emit( | |
'pickingstates.update', | |
_.omit(pickingstate.get({ plain: true }), ['createdAt', 'updatedAt']) | |
) | |
}) | |
}) | |
//STORE: | |
@action setState = state => { | |
_.keys(state).map(key => { | |
this.state[key] = state[key] | |
}) | |
} | |
//COMPONENT: | |
componentDidMount() { | |
this.socket = io(config.baseurl, { transports: ['websocket', 'polling'] }) | |
this.socket.on('pickingstates.update', pickingstate => { | |
this.setPickingState( | |
pickingstate.deliveryDate, | |
pickingstate.orderId, | |
pickingstate.productId, | |
pickingstate.state, | |
pickingstate.data, | |
false, | |
) | |
}) | |
this.props.store.loadPickingStates() | |
} | |
setPickingState = ( | |
date, | |
orderId, | |
productId, | |
state, | |
data = {}, | |
emit = true, | |
) => { | |
this.props.store.setState({ | |
pickingstates: _.assign({}, this.props.store.state.pickingstates, { | |
[`${date}-${orderId}-${productId}`]: { | |
state: state, | |
data: data, | |
}, | |
}), | |
}) | |
if (emit) { | |
this.socket.emit('pickingstates.update', { | |
deliveryDate: date, | |
orderId: orderId, | |
productId: productId, | |
state: state, | |
data: data, | |
}) | |
} | |
} | |
handleSetPickingState = event => { | |
this.props.setPickingState( | |
event.currentTarget.dataset.date, | |
event.currentTarget.dataset.orderid, | |
event.currentTarget.dataset.productid, | |
event.currentTarget.dataset.nextstate, | |
) | |
} | |
render() { | |
return ( | |
... | |
<a | |
onClick={this.handleSetPickingState} | |
data-date={state.selectedDate} | |
data-orderid={order.id} | |
data-productid={product.id} | |
data-nextstate={ | |
pickingstate === 'unchecked' ? 'checked' : 'unchecked' | |
} | |
/> | |
... | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment