0

I am using Grapgql for querying in React application. I have a query & mutation, both in the same component. Because of this, the variables defined error & data is repeated. Therefore it is showing an error in React as Identifiers already declared

Below is the code for the component:

function DisplayUsers() {
  let { id } = useParams();
  const { loading, error, data } = useQuery(LOAD_USERS_BY_ID, {
    variables: { id: parseInt(id) },
  });

  const [deleteUserById, { error, data }] = useMutation(DELETE_USER);

  const deleteUser = () => {
    deleteUserById({ variables: { id: id } });
  };

  useEffect(() => {
    if (data) {
      console.log(data);
      alert('Successful deletion');
      setTimeout(() => {
        <Redirect
          to={{
            pathname: '/view-users',
          }}
        />;
      }, 3000);
    }
  }, [data]);

  console.log(typeof id);
  console.log(data);
  if (loading) return <h4>Loading data...</h4>;
  return (
    data && (
      <div className='row'>
        <div className='col s12 m6 offset-m3' style={{ marginTop: '50px' }}>
          <div className='card'>
            <div className='card-content'>
              <span className='card-title'>
                {data.getUsersById.firstName} {data.getUsersById.lastName}
              </span>
              <p>Registerd Email: {data.getUsersById.email}</p>
              <p>Registerd Password: {data.getUsersById.password}</p>
              <p>User Id : {data.getUsersById.id}</p>
              <br />
              <div className='card-action'>
                <button
                  onClick={deleteUser}
                  className='waves-effect waves-light btn-small right'
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  );
}

How can it be overcome?

4

1 回答 1

1

You can provide different names like this

const { loading, error: userError, data: userData } = useQuery(LOAD_USERS_BY_ID, {
    variables: { id: parseInt(id) },
});

then use the new names in the rest of the code

OR

const userQuery = useQuery(LOAD_USERS_BY_ID, {
    variables: { id: parseInt(id) },
});

then use userQuery.data in rest of the code

于 2021-05-03T14:43:20.723 回答