jefFoo
jefFoo

Reputation: 109

multiple if statements in a React.js component

I am working on my portfolio and I bumped into this problem. This component gets tasks(array) and sortBy(either 'all', 'true', or 'false'). The problem is, even though I pass 'all' value of sortBy, the second if statement gets called.

const TaskListTable = ({ tasks, sortBy }) => {
  let filteredTasks;
  let sortByBoolean;
  if (sortBy === 'all') {
    filteredTasks = tasks;
  }
  if (sortBy === 'true' || 'false') {
    sortByBoolean = sortBy === 'true';
    filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
  }
  console.log(sortBy);
  console.log(sortByBoolean);
  console.log(filteredTasks);

  const withTasks = (
    <div className='task-table'>
      <UtilButton purpose='add' pushUrl='/task-add' />
      <div className='task-table-head'>
        <div>Date</div>
        <div>Task</div>
        <div>Status</div>
        <div></div>
      </div>
      {filteredTasks.map(({ _id, ...others }) => (
        <TaskList key={_id} id={_id} {...others} />
      ))}
    </div>
  );
  const withoutTasks = <UtilPage purpose='emptyData' />;

  return <Fragment>{tasks.length > 0 ? withTasks : withoutTasks}</Fragment>;
};

I solved this problem with this code below instead of using 2 if statements. But I'd still want to know why the code above with 2 if statements don't work.

const sortByBoolean = sortBy === 'true';
const filteredTasks = sortBy !== 'all' ? tasks.filter((task) => task.completed === sortByBoolean) : tasks;

thank you in advance

Upvotes: 1

Views: 711

Answers (3)

Stephan Bauer
Stephan Bauer

Reputation: 9249

This part...

if (sortBy === 'true' || 'false') {
  //...
}

...should be...

if (sortBy === 'true' || sortBy === 'false') {
  //...
}

You didn't check the condition if sortBy equals 'false' but you checked the value 'false' itself. This will return true because the string 'false' is truthy.
So currently both of your if statements are true and are executed.

Upvotes: 2

Anks
Anks

Reputation: 101

because your if condition is not as expected because both if will be executed to skip second if when first is passed add else

if (sortBy === 'all') {
  filteredTasks = tasks;
} else if (sortBy === 'true' || sortBy === 'false') {
  sortByBoolean = sortBy === 'true';
  filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
}

Upvotes: 0

Mehadi Hassan
Mehadi Hassan

Reputation: 1230

If you write two If statements consecutively then definately it will execute both of this two. This is the behaviour of If statement.

So you may used if else if method, also write || statement separately to solve this problem.

   if (sortBy === 'all') {
    filteredTasks = tasks;
  }
  else if (sortBy === 'true' || sortBy === 'false') {
    sortByBoolean = sortBy === 'true';
    filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
  }

Upvotes: 0

Related Questions