Home > Enterprise >  Can't remove the value and uncheck the item of checkbox?
Can't remove the value and uncheck the item of checkbox?

Time:11-26

Maybe the question is a little bit confusing because I'm confused. The problem I have listed categories in the database I fetched it and create a post. Now I'm trying to edit the post. The categories are in checkbox format if check it adds the setCategories state if uncheck it will remove from the state. I have fetched the post and saved categories for that particular post. I've shown them checked. Now I'm trying to change the categories I've added. I'm successful to add more but cannot remove it as well am unable to uncheck the checkbox. Please check this code...

I'm highlighted the onChange part with dashes

here is code

    import React, { useEffect, useState } from 'react';
    import { Alert, Button, Card, Container, Form } from 'react-bootstrap';
    import ReactMarkdown from 'react-markdown';
    import { useDispatch, useSelector } from 'react-redux';
    import { toast, ToastContainer } from 'react-toastify';
    import { listCategory } from '../actions/categoryActions';
    import { listPostDetails, updatePost } from '../actions/postActions';
    
    const EditPost = ({ history, match }) => {
      const postId = match.params.id;
    
      const [categories, setCategories] = useState([]);
    
      const dispatch = useDispatch();
    
      const userLogin = useSelector((state) => state.userLogin);
      const { userInfo } = userLogin;
    
      const categoryList = useSelector((state) => state.categoryList);
      const { categories: cateList } = categoryList;
    
      useEffect(() => {
        if (!userInfo) {
          history.push('/login');
        }
    
        if (!post || post._id !== postId) {
          dispatch(listPostDetails(postId));
        } else {
          setCategories(post.categories);
          console.log(categories);
        }
        dispatch(listCategory());
      }, [dispatch, history, userInfo, post, postId, categories]);
    
      const resetHandler = () => {
        setTitle('');
        setImg('');
        setCategories('');
        setDesc('');
      };
    
      const submitHandler = (e) => {
        e.preventDefault();
        dispatch(updatePost(postId, title, desc, img, categories));
        resetHandler();
        history.push('/my_posts');
      };
    
      return (
        <div className=" createPost mt-4 py-4">
          <ToastContainer />
          <Container>
            <h2>EDIT POST</h2>
            <Form onSubmit={submitHandler}>
              <Form.Group controlId="category" className="mb-2">
                <Form.Label>Select Categories</Form.Label>
                <br />
                {cateList?.map((cate) => (
                  <Form.Check
                    inline
                    key={cate._id}
                    type="checkbox"
                    label={cate.name}
                    checked={categories.includes(cate.name)}
------------------------------------------------------------------------------------------
                    onChange={(e) => {
                      if (e.target.checked) {
                        setCategories([categories.push(cate.name)]);
                      } else {
                        setCategories(
                          categories?.filter((cat) => cat !== cate.name)
                        );
                      }
                    }}
-------------------------------------------------------------------------------------------
                  />
                ))}
              </Form.Group>
              <Button
                type="submit"
                variant="success"
                style={{ letterSpacing: '2px', fontWeight: 'bold' }}>
                UPDATE
              </Button>
            </Form>
          </Container>
        </div>
      );
    };
    
    export default EditPost;

CodePudding user response:

I think the problem is on useEffect method you are console.log(categories) it keeps on refreshing the state and not allowing you to add or remove items. first remove the console.log(categories) and also categories dependencies from useEffect and use this setCategories([...categories, cate.name]); instead of this setCategories([categories.push(cate.name)]);. You shouldn't change categories directly

CodePudding user response:

You shouldn't change categories directly. So, instead of

setCategories([categories.push(cate.name)]);

try

setCategories([...categories, cate.name]);
  • Related