I am having a component connected to a redux store. I do get data over a socket connection and dispatch an action to the store on the response. I would expect that the component would receive this new value in nProps of componentDidUpdate(). However an update is triggered and instead the new values arrive already in this.props:
Expected Outcome:
Component mounted | this.props.videos: null
Component updated | this.props.videos: null | nProps.videos: (3) [{鈥, {鈥, {鈥]
...
Given Outcome:
Component mounted | this.props.videos: null
Component updated | this.props.videos: (3) [{鈥, {鈥, {鈥] | nProps.videos: null
Component updated | this.props.videos: (3) [{鈥, {鈥, {鈥] | nProps.videos: (3) [{鈥, {鈥, {鈥]
...
Here is my source code:
// channel.js
import store from './store';
import socket from './socket'
let configureChannel = function (channel) {
// join channel and add new videos to store
channel.join()
.receive("ok", res => {
store.dispatch({ type: "GET_VIDEO_LIST", res.videos })
})
}
// configure channel on first import and export
let channel = socket.channel("public")
configureChannel(channel)
export default channel
// reducer.js
import _ from 'lodash'
const videoReducer = function(state = { videos: null }, action) {
switch(action.type) {
case "GET_VIDEO_LIST":
return _.create( state, { videos : _.cloneDeep(action.videos) })
}
return state
}
// component.js
import React from 'react'
import { connect } from 'react-redux'
import channel from './channel'
class SimulationContainer extends React.Component {
constructor(props){
super(props)
console.log("Component mounted | this.props.videos:", this.props.videos)
}
componentDidUpdate(nProps){
console.log("Component updated | this.props.videos: ", this.props.videos, "|", nProps.videos
}
}
const mapStateToProps = function(store) {
return { videos: store.videoState.videos }
}
export default connect(mapStateToProps)(SimulationContainer)
You're using the wrong lifecycle method. You want componentWillReceiveProps(), which receives nextProps as its argument. componentDidUpdate receives prevProps instead, and by the time cDU runs, this.props has already been updated.
See https://reactjs.org/docs/react-component.html#componentdidupdate .
thanks a ton! :) learned a lot today 馃憤
I know this is an old issue, but I'm having the same problem. I'm using componentDidUpdate because componentWillReceiveProps() is now UNSAFE. Is there another solution?
Most helpful comment
I know this is an old issue, but I'm having the same problem. I'm using
componentDidUpdatebecausecomponentWillReceiveProps()is nowUNSAFE. Is there another solution?