Home > Net >  reactjs ---> useReducer topic
reactjs ---> useReducer topic

Time:11-14

in the reactjs I am not understand the below code please help me in this

...todo, complete: !todo.complete

according to me first ...todo is the spread array, and after comma the condition has been implemented on it.

CodePudding user response:

It's vanilla JavaScript, nothing related to react here

This is not a condition

!false -> true
!true -> false

Doing this:

const todo = {
  name: 'Something to do',
  complete: false
}

const newTodo = {
  ...todo,
  complete: !todo.complete
}

Results in:

{
  name: 'Something to do',
  complete: true
}

CodePudding user response:

this is spread operator.

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object.

you can read more in this link

CodePudding user response:

This is the Spread Operator, just plain JS, nothing related to React.

When you use the spread operator:

const todo = {
  completed: false,
  title: "Test"
};

const sameTodo = { ...todo };

The sameTodo variable will be the same as the todo variable.

// sameTodo
{
  completed: false,
  title: "Test"
}

In the example you gave in the question, it will first create a new object and then add the values of the todo object to it

Eg:

const todo = {
  completed: false,
  title: "Something"
}

/*
Value of `changedTodo`:

{
  completed: false,
  title: "Something"
}

*/
const changedTodo = {
  ...todo
}

And then it says

complete: !todo.complete

The ! Mark is a logical 'Not' operator, it will change a value to its opposite.

Eg:

// True will become false & false will become true
!true --> false
!false --> true

So when we get back to changedTodo, we can add the operator to the completed property:

const changedTodo = {
  ...todo,
  completed: !todo.completed
}

And when you assign a property that already exists in an object that you are spreading, it will overwrite it.

So, here the todo object already has a completed property, so when we use completed: !todo.completed, it will overwrite what was on the todo object and change it to it's opposite.

Since here the todo object has the completed property as false, it will turn to true

So in the end, we get this:

const changedTodo = {
  title: "Something",
  completed: true
}

By the way, this has nothing to do with React or useReducer. This is plain vanilla Javascript.

Hope this helps.

  • Related