Alex Kleymen
Alex Kleymen

Reputation: 31

useState, react hook with contexAPI

i have a very strange problem. to make a long story short im using react hooks with context api. when i'm trying to remove item from my state with filter the use state function doesn't start

my data looks like this: enter image description here

and my code looks like this, the problem is with deleteUser function: (added only the relevant part):

const UserContextProvider = (props) => {
const[users,setUsers] = useState([])

const addUser = (user) =>{
    setUsers([...users,user])
}

const updateUser = (obj) =>{
    deleteUser(obj.UserName)
    addUser(obj)
}

const deleteUser = (us) =>{
 //not working
 setUsers(users.filter(u=>u.UserName!=us))

 //working
let temp  = [...users]
 temp = temp.filter(el=>el.UserName!=us)
 setUsers([...temp]) 
}

Upvotes: 1

Views: 79

Answers (2)

Fahad Shinwari
Fahad Shinwari

Reputation: 968

What your problem is you are not using !== instead you have written !=

const deleteUser = (us) =>{
 //Add an equal sign it will work
 setUsers(users.filter(u=>u.UserName!==us))

Upvotes: 1

Jason
Jason

Reputation: 367

try this instead...

const deleteUser = (us) =>{
 setUsers(previousUsers => previousUsers.filter(u => u.UserName !== us))
}

Upvotes: 1

Related Questions