D
D
Danoneko2022-04-14 20:00:18
JavaScript
Danoneko, 2022-04-14 20:00:18

How to move the called function to useEffect?

Constant error "React Hook useEffect has a missing dependency: 'userData'. Either include it or remove the dependency array react-hooks/exhaustive-deps"

It has been suggested on the internet to move the function inside the hook. I'm new to react and don't know how to fix this if the handleChange function is called below. Please tell me how to do it?

import data from "../Data/data";

const userData = data;
const [users, setUsers] = useState([]);
const [selectedUser, setSelectedUser] = useState([]);

  useEffect(() => {
    setUsers(userData);
  }, []);

  // console.log('selectedUser);


  const handleChange = (e, data) => {
    const { name, checked } = e.target;
    if (checked) {
      if (name === "allSelect") {
        setSelectedUser(users);
      } else {
        setSelectedUser([...selectedUser, data]);
      }
    } else {
      if (name === "allSelect") {
        setSelectedUser([]);
      } else {
        let tempuser = selectedUser.filter((item) => item.id !== data.id);
        setSelectedUser(tempuser);
      }
    }
  };

return(
<input
                    type="checkbox"
                    className="form-check-input"
                    name="allSelect"
                    // allSelect selected when both length equal
                    // slecteduser === allUser
                    checked={selectedUser?.length === users?.length}
                    onChange={(e) => handleChange(e, users)}
                  />
)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2022-04-14
@Danoneko

if data is just imported, then throw away useEffect and write
const [users, setUsers] = useState(data);

S
sevenov_elevenov, 2022-04-14
@sevenov_elevenov

This is not exactly an error, this is a warning linter, it says that useEffectyou need to specify a dependency on userData for:

useEffect(() => {
    setUsers(userData);
  }, [userData]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question