dimanche 14 juin 2020

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

Aucun commentaire:

Enregistrer un commentaire