Home > Back-end >  Adding a new item to list in ReactJS functional Component not updating UI
Adding a new item to list in ReactJS functional Component not updating UI

Time:10-08

I have a list as follows

const[users,setUsers]=useState([]);

to dynamically add a new user and update the UI i have a function as below

const addNewUser = newUser => {
      setUsers(previousUsers=>{
            //only add user if he has not been added
            let existingUser = previousUsers.find((x)=>x.id===newUser.id);
            if(!existingUser){
                previousUsers.push(newUser);
            }
            return previousUsers;
        });
}

Unfortunately the above code is not updating the UI. This is weird.

What could I be doing wrong?

CodePudding user response:

I would do the check outside of the set state:

function addNewUser(newUser) {
  const existingUser = users.find(user => user.id === newUser.id);
  if (!existingUser) {
    setUsers(prev => ([...prev, newUser]));
  }
}

CodePudding user response:

The reason that the UI is not re-rendering is because state value is not changed. If you want to use arrays or objects in React State, you have to create a copy of the value before modifying it. You can find the basic example of doing it below:

const [todos, setTodos] = useState([]);
const handleAdd = (todo) => {
    const newTodos = [...todos];
    newTodos.push(todo);
    setTodos(newTodos);
}
  • Related