I'm trying to use Redis to store and get a boolean for my toggle function.
The dependecy what I'm using is redis-js
I can set the value false
with key to redis but getting the valu from redis is always false
.
Say first store the key value to Redis
redis.set('myKey', 'false');
Get the value
let toggle = redis.get('myKey');
toggle = !toggle;
Store
redis.set('myKey', toggle);
Get
const checkStatus = redis.get('myKey');
return checkStatus;
I'm expecting the output will be true -> false
if executed the function two times.
Redis cache backend doesn't allow storing bool values.
Object Storing Procedure. In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases.
In Redis, we have the advantage of storing both strings and collections of strings as values. A string value cannot exceed 512 MB of text or binary data. However, it can store any type of data, like text, integers, floats, videos, images, and audio files.
Unlike other key-value data stores that offer limited data structures, Redis has a vast variety of data structures to meet your application needs. Redis data types include: Strings – text or binary data up to 512MB in size. Lists – a collection of Strings in the order they were added.
For your toogle to work you've to explicitly check if the value you get is equal to the string 'false'
.
let toggle = redis.get('myKey');
toggle = toogle === 'false'
Converting the string 'false'
to boolean results to true
not false
and negating it you get false
.
From MDN
All other values, including any object or the string
"false"
, create an object with an initial value oftrue
Here's an illustration:
const val = 'false'
const toggle = !val; // this is equivalent to !Boolean(val)
const bool = Boolean(val) // get boolean
const negated = !bool // negate
console.log('toggle: ', toggle);
console.log('bool: ', bool); // Boolean("false") gives true
console.log('negated: ', negated);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With