React-Redux : re render child component on mapStateToProps in parent change doesn't work

Viewed 256

I'm new to redux, and I'm trying to make a component reactive. I want to re-render the MoveList component when the prop I'm passing down from parent mapStateToProps changes and it's not working.

I tried giving a key to the movelist component but it didn't work, and Im not sure how else to approach this

Parent component:

    async componentDidMount() {
        this.loadContact();
        this.loadUser();
    }

    loadContact() {
        const id = this.props.match.params.id;
        this.props.loadContactById(id);
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.match.params.id !== this.props.match.params.id) {
            this.loadContact();
        }
    }

    transferCoins = (amount) => {
        const { contact } = this.props
        console.log('amount', amount);

        this.props.addMove(contact, amount)
        console.log(this.props.user);

    }

    get filteredMoves() {
        const moves = this.props.user.moves
        return moves.filter(move => move.toId === this.props.contact._id)
    }


    render() {
        const { user } = this.props;
        const title = (contact) ? 'Your Moves:' : ''


        if (!user) {
            return <div> <img src={loadingSvg} /></div>;
        }

        return (
            <div className="conact-deatils">
                { <MoveList className="move-list-cmp" title={title} moveList={this.props.user.moves} />}
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        user: state.user.currUser
    };
};

const mapDispatchToProps = {
    loadContactById,
    saveContact,
    addMove
};

export default connect(mapStateToProps, mapDispatchToProps)(ContactDetailsPage);

Child component: moveList

export const MoveList = (props) => {    
    return (

        <div className="moves-list">
        <div className="title">{props.title}</div>
        <hr/>
            {props.moveList.map(move => {
                return (
                    <ul className="move" key={move._id}>
                        {props.isFullList && <li>Name: {move.to}</li>}
                        <li>Amount: {move.amount}</li>
                    </ul>
                )
            })}
        </div>
    )
}

1 Answers

at the end the problem was that the parent component didn't re-render when i called the addMove dispatch. i didn't deep copied the array of moves object, and react don't know it need to re-render the component. i made a JSON.parse(JSON.stringify deep copy and the component.

Related