title: ReactJS - Like and Unlike using same button - updating without refreshing page
body: <p>I'm following a Udemy course and they have an unlike and like button where they're separate from each other. I want to try to make them into 1 button, so buttons would toggle and update the number of likes without refreshing the page.</p>
  
  <p>I have something like this in the return() within a functional component</p>
  
  <pre><code>{posts.filter(item =&gt; item.user.toString() === user).length &gt; 0 ? (
    &lt;button onClick={e =&gt; unlike(_id)}&gt;Unlike&lt;/button&gt;
  ) : (
    &lt;button onClick={e =&gt; like(_id)}&gt;Like&lt;/button&gt;
  )}
  </code></pre>
  
  <p>This ony renders once page loads, and it will only render either Unlike or Like depending on the conditional statement. User can only like once, so if user already liked a post, on page load, it will load Unlike button, if user clicks Unlike, it will stay Unlike, and not refresh the view.</p>
  
  <p>I'd like to update this also:</p>
  
  <pre><code>{posts.length}
  </code></pre>
  
  <p>How would I go about doing this without refreshing the page and that it'll rerender on user's action?</p>
  
  <hr>
  
  <p><strong>actions/post.js</strong></p>
  
  <pre><code>// Like
  export const like = id =&gt; async dispatch =&gt; {
    try {
      const res = await axios.put(`/api/posts/like/${id}`);
  
      dispatch({
        type: UPDATE_LIKES,
        payload: { id, likes: res.data }
      });
    } catch (err) {
  
    }
  };
  
  // Unlike
  export const unlike = id =&gt; async dispatch =&gt; {
    try {
      const res = await axios.put(`/api/posts/unlike/${id}`);
  
      dispatch({
        type: UPDATE_LIKES,
        payload: { id, likes: res.data }
      });
    } catch (err) {
  
    }
  };
  </code></pre>
  
  <hr>
  
  <p><strong>reducers/post.js</strong></p>
  
  <pre><code>import {
    GET_POSTS,
    POST_ERROR,
    UPDATE_LIKES,
    ADD_POST
  } from '../actions/types';
  
  const initialState = {
    posts: [],
    post: null,
    loading: true,
    error: {}
  };
  
  export default function(state = initialState, action) {
    const { type, payload } = action;
  
    switch (type) {
      case GET_POSTS:
        return {
          ...state,
          posts: payload,
          loading: false
        };
      case ADD_POST:
        return {
          ...state,
          posts: [...state.posts, payload],
          loading: false
        };
      case POST_ERROR:
        return {
          ...state,
          posts: payload,
          loading: false
        };
      case UPDATE_LIKES:
        return {
          ...state,
          posts: state.posts.map(post =&gt;
            post._id === payload.id
              ? { ...post, likes: payload.likes }
              : post
          ),
          loading: false
        };
      default:
        return state;
    }
  }
  </code></pre>