Hayko
Hayko

Reputation: 3

how can I delete the element in react js

I want to create simple application with react js, which should show the users in the display and then when I click on the delete button, it should delete the following item, however I am having some errors.

import React, { useEffect, useState } from 'react'
const App = () => {
  const [users, setUsers] = useState([])

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((users) => {
        setUsers(users);
      })
  }, [users]);

  const deleteMe = () => {
    setUsers(prevState => {
      return prevState.filter(e => e.name)
    })
  }

  return (
    <>
      {users.map((user) => {
        return (
          <>
            <div> {user.name}
              <button onClick={deleteMe}> Delete </button>
              {/* <button onClick={}> Update </button> */}
            </div>
          </>
        )
      })}
    </>
  )
}

export default App

Upvotes: 0

Views: 1617

Answers (3)

Maharajan
Maharajan

Reputation: 188

try this , element get deleted and not refresh

import React, { useEffect, useState } from 'react';
const Example = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);
  const fetchData = async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const data = await response.json();
    setUsers(data);
    // .then()
    // .then(users => {
    //   setUsers(users);
    // });
  };
  const deleteMe = index => {
    setUsers(prevState => {
      console.log(prevState);
      return prevState.filter((e, i) => i !== index);
    });
  };

  return (
    <div>
      {users.map((user, i) => {
        return (
          <div>
            {' '}
            {user.name}
            <button onClick={() => deleteMe(i)}> Delete </button>
            {/* <button onClick={}> Update </button> */}
          </div>
        );
      })}
    </div>
  );
};

export default Example;

Upvotes: 0

Andy
Andy

Reputation: 63550

Look at the useEffect code. Because you have users as a dependency the effect will pick up any changes to that state. State changes, you make an API call, then update users, the effect gets called again on the next render, you update users in state, users gets updated again... etc.

It sounds like you just need an empty dependency array so that the effect is only called once when the component is rendered.

useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((response) => response.json())
    .then((users) => {
      setUsers(users);
    })
}, []);

Upvotes: 1

Iv&#225;n
Iv&#225;n

Reputation: 1060

To remove the user, the callback (onClick) must have enough information to identify the user to be removed.

In this example, you have some options:

  1. Remove by name. Only if the user names are unique:
const deleteMe = (userName) => {
    setUsers(prevState => {
        return prevState.filter(e => e.name !== userName)
    })
}

return (
    <>
        {users.map((user) => {
            return (
                <>
                    <div> {user.name}
                    <button onClick={() => deleteMe(user.name)}> Delete </button>
                    {/* <button onClick={}> Update </button> */}
                    </div>
                </>
            )
        })}
    </>
)
  1. Remove by the element itself. Only if the element isn't repeated in the array (the object itself):
const deleteMe = (user) => {
    setUsers(prevState => {
        return prevState.filter(e => e !== user)
    })
}

return (
    <>
        {users.map((user) => {
            return (
                <>
                    <div> {user.name}
                    <button onClick={() => deleteMe(user)}> Delete </button>
                    {/* <button onClick={}> Update </button> */}
                    </div>
                </>
            )
        })}
    </>
)
  1. Remove by the array index. Only if the state is an array, usually:
const deleteMe = (userIndex) => {
    setUsers(prevState => {
        return prevState.filter((e, i) => i !== userIndex)
    })
}

return (
    <>
        {users.map((user, i) => {
            return (
                <>
                    <div> {user.name}
                    <button onClick={() => deleteMe(i)}> Delete </button>
                    {/* <button onClick={}> Update </button> */}
                    </div>
                </>
            )
        })}
    </>
)

See how a second parameter i was added to the map and filter functions. That is usually ignored, but it may be useful sometimes.

As this method may fail if the array is reordered of an element is added/removed between the render and the callback, I wouldn't recommend it unless there is no other alternative.

Upvotes: 1

Related Questions