React Select All Checkbox not working properly

Viewed 183

I am trying to implement Select All check box functionality to delete all/ multiple posts in one click

enter image description here

React Component:-

function AllPosts() {
  const dispatch = useDispatch();

  const [page, setPage] = useState(0);

  const { posts } = useSelector((state) => state.posts);

  const [deletePosts, setDeletePosts] = useState([]);

  const [postsData, setPostsData] = useState([]);

  const { totalPages } = posts;

  // get posts
  useEffect(() => {
    dispatch(getPosts(page));
  }, [dispatch, page]);


  // setting posts state
  useEffect(() => {
    setPostsData(posts?.Allposts);
  }, [posts]);


//   ***********************************************
//   *                                             * 
//   *         Problem Part                        *
//   *                                           *    
//   *                                             *
//   ***********************************************


  const handleAllChecked = (e) => {

    // checkbox name is id of the posts
    const { name, checked } = e.target;
      
    // update list for IDs of selected checkbox 
    let updateList;


    if (name === "CheckAll") {

      // cant add post._id as it shows undefined  
      // deletPosts is an array of Ids to delete.
      postsData?.map((post) => [...deletePosts, post._id]);

      // check all checkboxes
      let tempPost = postsData?.map((post) => {
        return { ...post, isChecked: checked };
      });

      setPostsData(tempPost);

    } else 
    {
      let tempPost = postsData?.map((post) =>
        post._id === name ? { ...post, isChecked: checked } : post
      );
    
      // add IDs of posts to delete to deletePosts Array
      if (deletePosts.includes(name)) {
        updateList = deletePosts.filter((item) => item !== name);
      } else {
        updateList = [...deletePosts, name];
      }
    
      // set deletePosts array
      setDeletePosts(updateList);

      setPostsData(tempPost);
    }
  };


  // Delete Posts
  const handleDelete = () => {
    dispatch(deletePost(deletePosts));
  };

  return (
    <>
      <div className="all-posts-wrapper">
        <div className="all-posts-main-container">
          <ActionBar>
              {/* *******************************************
              *
              *     Check Box and Delete Button component
              *
              *
              *************************************************/}
            <ActionBarBtns
              checked={
                !postsData?.some((post) => post?.isChecked !== true)
              }
              name="CheckAll"
              onChange={handleAllChecked}
              handleDelete={handleDelete}
            />
          </ActionBar>
          <div className="all-posts-main-content">
              <div className="all-posts">
                <>
                  {typeof postsData === typeof [] && (
                    <>
                      {postsData.map((post, index) => (
                        <Post
                          key={post._id}
                          postId={post._id}
                          postSubject={post.subject}
                          checked={post?.isChecked || false}
                          onChange={handleAllChecked}
                          checkBoxName={post._id}
                        />
                      ))}
                    </>
                  )}
                </>
              </div>
            </div>
          </div>
        </div>
    </>
  );
}
export default AllPosts;

The problem part of the code

const handleAllChecked = (e) => {

    // checkbox name is id of the posts
    const { name, checked } = e.target;
      
    // update list for IDs of selected checkbox 
    let updateList;


    if (name === "CheckAll") {

      // cant add post._id as it shows undefined  
      // deletPosts is an array of Ids to delete.

      postsData?.map((post) => [...deletePosts, post._id]);

      // check all checkboxes
      let tempPost = postsData?.map((post) => {
        return { ...post, isChecked: checked };
      });

      setPostsData(tempPost);

    } else 
    {
      let tempPost = postsData?.map((post) =>
        post._id === name ? { ...post, isChecked: checked } : post
      );
    
      // add IDs of posts to delete to deletePosts Array
      if (deletePosts.includes(name)) {
        updateList = deletePosts.filter((item) => item !== name);
      } else {
        updateList = [...deletePosts, name];
      }
    
      // set deletePosts array
      setDeletePosts(updateList);

      setPostsData(tempPost);
    }
  };

My Intention:-

  1. whenever any Checkbox is selected its Id should be added to the deletePosts array
  2. whenever the Select All checkbox is checked all posts Ids should be added to deletePosts array

Code's current working:-

  • If any or all posts checkbox is checked then their IDs are added to deletePosts array. This Works

  • If the Select All checkbox is checked then all posts IDs are not added to deletePosts the deletePosts array is undefined when Select All is checked.

0 Answers
Related