F
F
Flakelf2019-04-22 09:40:38
React
Flakelf, 2019-04-22 09:40:38

What's the best way to make a side effect?

Evening at the house.
Interested in how to make a side effect. Specifically:
I have a Card component that looks like this: 5cbd60ca8c69f530958520.png
Code:

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';

const Styles = styled.div`
    .row {
        padding-top: 100px; padding-bottom: 500px
    }

    .card {
        max-width: 22rem;
    }

    .likes-section {
        display: inline
    }

    .heart-image {
        float: left;
    }

    .likes-count {
        font-size: 18px;
        padding-left: 46px;
        padding-top: 4px;
    }
`;

const Card = (props) => {

    console.log(props);

    const [state, setState] = useState({
        count: 22,
        isLiked: false
    });

    useEffect(() => {
        console.log(state);
    })

    const incrementLikes = () => {
        setState({
            ...state,
            count: !state.isLiked ? state.count + 1 : state.count - 1,
            isLiked: !state.isLiked
        });
    }

    return (
        <Styles>    
            <div className="container">
                <div className="row justify-content-center">
                    <div className="card">
                        <img className="card-img-top" src="https://pp.userapi.com/c852020/v852020640/a0273/sYULVSgkNZo.jpg"
                            alt="img here" />
                        <div className="card-body">
                            <h5 className="card-title">simple anime tyan with diet pepsi сola</h5>
                            <div className="likes-section">
                                <img onClick={incrementLikes} className="heart-image" src={state.isLiked ? 'https://img.icons8.com/color/34/000000/hearts.png' : 'https://img.icons8.com/ios/34/000000/hearts.png'} />
                                <p className="likes-count">{state.count}</p>
                                <p>{state.isLiked}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Styles>
    )
}

const mapStateToProps = state => {
    console.log(state);
    return state;
}

export default connect(mapStateToProps, null)(Card);

By clicking on the heart, a like should be put and the request will work, it is intuitively clear with what. How to implement better? How to get the required card in useEffect key?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-04-22
@flakelf

You, in a good way, need to pass an action to the card that takes the post ID and initiates a request to the server.

const mapDispatchToProps = {
  likePost,
};

I
irishmann, 2019-04-22
@irishmann

use data-* attributes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question