2

I have some columns (infected and absence) in my MySQL database that are stored as TINYINT(1).

When I do a simple

app.get("/users", (req, res) => {
  const sql = `SELECT * from users`;
  connection.query(sql, (err, results) => {
    if (err) {
      return res.send(err);
    } else {
      return res.json({ results });
    }
  });
});

in my backend and a

  useEffect(() => {
    axios
      .get(`${config.server}/users`)
      .then((result) => {
        setUsers(result.data.results);
      })
      .catch((error) => console.error(error));
  }, [setUsers]);

in my ReactJS frontend, I am not able to do something like:

users.filter((u) => u.infected);

Only

users.filter((u) => u.infected === 1);

is working.

As using users.filter((u) => u.infected); is more intuitive for me, I want to know, how can I handle this in best practice?

  1. Do I need to store my values in another type?
  2. Do I need to SELECT the values in a different way?
  3. Do I need to translate the values from 1 to TRUE and 0 to FALSE after querying them?
  4. Do I need to translate the values in the frontend after the get request?

I try to avoid using 4. unless this is not the best deal, because my frontend already expects booleans all over the place (I switched the database to MySQL).

Nick Rick
  • 75
  • 6
  • "I am not able to do something like:" --- why? What does "am not able" exactly mean? – zerkms Apr 27 '21 at 08:14
  • I don't know? It's not working - only `=== 1` is working. Maybe this is because `typeof u.infected` is a number? – Nick Rick Apr 27 '21 at 08:17
  • Can you show `console.log(JSON.stringify(u.infected))` for both positive and negative values? – zerkms Apr 27 '21 at 08:17
  • It's logging `0` and `1` – Nick Rick Apr 27 '21 at 08:41
  • It cannot log `0` and `1`, are there quotes around? Can you copy the **exact unmodified** output. Because if there are literally `0` and `1` values then `users.filter((u) => u.infected)` would have worked. – zerkms Apr 27 '21 at 08:42
  • I receive `1 1 string number false` for `console.log(JSON.stringify(infected),infected,typeof JSON.stringify(infected),typeof infected,JSON.stringify(infected) === infected);` – Nick Rick Apr 27 '21 at 13:35
  • and for the non 1 row? – zerkms Apr 28 '21 at 02:42
  • I get `0 0 string number false` – Nick Rick Apr 28 '21 at 07:05
  • 1
    Given they are numbers and are either `0` or `1` - `users.filter((u) => u.infected)` would work. If the behaviour is still not what you expect - then the **actual data** is not what you think it is and you should provide some code that actually demonstrates the problem. – zerkms Apr 28 '21 at 09:53

1 Answers1

1

Try using !! they will convert the value to a boolean type. It's equivalent with: Boolean(anyValue).

users.filter(u => !!u.infected);

Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29