简体   繁体   中英

In React.js the onClick function is not showing details without page refresh

I am trying to create a line and dislike button in React.js. I have two tags that contains google icons and upon clicking the icons they should change in realtime without having to refresh the page .

But they are not changing without page refresh . I am using a MacBook Air and I am using both Safari browser and Brave browser but it is not working.

The coding of my page is as follows:-


import React, { useState, useEffect, useContext } from 'react';
import {UserContext} from '../../App';

const Home = () => {

    const [data, setData] = useState([]);
    const { state, dispatch } = useContext(UserContext); // eslint-disable-line

    useEffect(() => {
        fetch('/allpost', {
            headers: {
                "Authorization": "Bearer " + localStorage.getItem("jwt")
            }
        }).then(res => res.json()).then(result => {
            setData(result.posts);
        });
    }, []);

    const likePost = (id) => {
        fetch('/like', {
            method: "put",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + localStorage.getItem("jwt")
            },
            body: JSON.stringify({
                postId: id
            })
        }).then(res => res.json()).then(result => {
            const newData = data.map(item => {
                if (item._id == result._id) { // eslint-disable-line
                    return result;
                } else {
                    return item;
                }
            })
            setData(newData);
        }).catch(err => {
            console.log(err);
        });
    }

    const dislikePost = (id) => {
        fetch('/dislike', {
            method: "put",
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + localStorage.getItem("jwt")
            },
            body: JSON.stringify({
                postId: id
            })
        }).then(res => res.json()).then(result => {
            const newData = data.map(item => {
                if (item._id == result._id) { // eslint-disable-line
                    return result;
                } else {
                    return item;
                }
            })
            setData(newData);
        }).catch(err => {
            console.log(err);
        });
    }

    return (
        <div className="home">
            {
                data.map(item => {
                    return (
                        <div className="card home-card" style={{ borderRadius:"6px" }} key={item._id}>
                            <h6 style={{ paddingLeft: "10px", paddingTop:"10px", fontSize:"17px" }}>{ item.postedBy.name }</h6>
                            <div className="card-image">
                                <img src={ item.photo } style={{ paddingLeft:"6px", paddingRight:"6px" }} alt="Posted photograph" />
                            </div>
                            <div className="card-content">

                                {item.likes.includes(state._id)
                                    ?
                                        <i className="material-icons" style={{ color: "red" }} onClick={() => { dislikePost(item._id) }}>favorite_border</i>
                                    :
                                        <i className="material-icons" style={{ color: "red" }} onClick={() => {likePost(item._id)}}>favorite</i>
                                    
                                }
                                
                                <h6>{item.likes.length} likes</h6>
                                <h6>{ item.title }</h6>
                                <p>{ item.body }</p>
                                <input type="text" placeholder="Add a comment here." />
                            </div>
                        </div>
                    );
                })
            }
        </div>
    );
}

export default Home;

I am specifically mentioning where my icon change logic is written. It is as follows:


    <div className="card-content">

         {item.likes.includes(state._id)
              ?
               <i className="material-icons" style={{ color: "red" }} onClick={() => { dislikePost(item._id) }}>favorite_border</i>
              :
               <i className="material-icons" style={{ color: "red" }} onClick={() => {likePost(item._id)}}>favorite</i>
                                    
         }
                                
         <h6>{item.likes.length} likes</h6>
         <h6>{ item.title }</h6>
         <p>{ item.body }</p>
         <input type="text" placeholder="Add a comment here." />
    </div>

This is not relevant for this question. But if you are up for an refactor, then i would suggest you to change the likePost and dislikePost functions into one function. Because both the functions does the same except that they have a different url which you can pass as a function argument.

 const updatePostLikes = (id, url) => {
    fetch(url, {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + localStorage.getItem('jwt'),
      },
      body: JSON.stringify({
        postId: id,
      }),
    })
      .then((res) => res.json())
      .then((result) => {
        const newData = data.map((item) => {
          if (item._id == result._id) {
            // eslint-disable-line
            return result;
          } else {
            return item;
          }
        });
        setData(newData);
      })
      .catch((err) => {
        console.log(err);
      });
  }

And when click on the like and dislike button you can now do this

updatePostLikes(item._id, '/like') // for likes

updatePostLikes(item._id, '/dislike') // for dislikes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM