Reputation: 45
I' am trying to use props coming from redux as a starting point for rendering my state-full component like this:
const MyComp = (props) => {
const initState = {
newAttribs: [...props.attribs]
};
const [state, setState] = useState(initState)
console.log(state)
};
const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));
But if I console.log(state)
it shows empty array for newAttribs
even though in initState newAttribs
are there.
Can someone shed some light on how to do this properly? Thanks.
EDIT:
I've made an error while posting code snippet, I updated it now.
const mapStateToProps
and const mapDispatchToProps
obviously have to be outside of the component scope and they are.
Upvotes: 3
Views: 11360
Reputation: 282030
There are three things that you need to take care of
mapStateToProps
and mapDispatchToProps
should be defined outside of the component scopeprops.attribs
changes you need to update your component state which you can do using useEffect
Example
const MyComp = (props) => {
const initState = {
newAttribs: [...props.attribs]
};
const [state, setState] = useState(initState)
useEffect (() => {
setState({ ...state, newAttribs: [...props.attribs] })
}, [props.attribs])
console.log(state)
};
const mapStateToProps = (fromRedux) => {...};
const mapDispatchToProps = (dispatch) => {...};
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(MyComp));
If the data from redux store is available before initial mount you will see it in console.log
Upvotes: 6