Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3140

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T11:56:12+00:00 2024-11-26T11:56:12+00:00

State Management with a Single Line of Code

  • 61k

If you're like me and feel that there has to be an easier way of state-management, then you'd like what ActiveJS can do for you.

I feel like I'm selling snake-oil, but I spent the last 10 months trying to make state-management as intuitive and easy as possible because I couldn't stand the state-management in the state it is right now.

For efficient state-management, we need a few things

  • data structures that are type-safe
  • data structures that can emit events on mutation
  • data structures that can guarantee immutability
  • data structures that can be persisted through sessions

The title promised all this in one line of code, so here it is.

const dataUnit = new DictUnit({  id: 'data', immutable: true, persistent: true, cacheSize: Infinity,  initialValue: {a: 1} }) // every option is optional, including the initialValue // DictUnit has empty object {} as it's default value 
Enter fullscreen mode Exit fullscreen mode

(Okay 4 lines, but I formatted it so you don't have to scroll 🙂

JavaScript doesn't have anything like that, that's why ActiveJS came into existence, and with it came reactive data structures called Units, one of them is DictUnit, that stores and ensures a dictionary object value at all times.

You might have already got a feeling from the configuration options we passed to the DictUnit and guessed what it's all about, but to elaborate DictUnit is:

  • Observable
  • Reactive
  • Type-Safe
  • Immutable
  • Persistent, and
  • Cache-Enabled

Let's see what that means in the language we all understand, the code:

Observable

DictUnit extends RxJS Observable class, so you can subscribe to it and apply all the RxJS operators on it just as you would on an Observable.

// subscribe for the value dataUnit.subscribe(value => console.log(value)) // logs {a: 1} immediately and will log future values  dataUnit instanceof Observable; // true 
Enter fullscreen mode Exit fullscreen mode

Reactive

When you update the value of a DictUnit it emits it to all the observers so that they get access to the latest value.

// non-functional dispatch dataUnit.dispatch({b: 2, c: 3}) // observers get {b: 2, c: 3}  // now dataUnit's value is {b: 2, c: 3}  // functional-dispatch dataUnit.dispatch(value => {return {...value, d: 4}}) // observers get {b: 2, c: 3, d: 4}  // we don't have to dispatch new values manually, // DictUnit provides a better way to update properties  // update a single property dataUnit.set('d', 5) // observers get {b: 2, c: 3, d: 5}  // delete properties dataUnit.delete('b', 'd') // 'b' and 'd' got yeeted // observers get {c: 3}  // update multiple properties dataUnit.assign({a: 1, b: 2}) // observers get {a: 1, b: 2, c: 3} 
Enter fullscreen mode Exit fullscreen mode

Type-Safe

A DictUnit ensures that at all times the value is always a dictionary object, it'll ignore any invalid value dispatch.

dataUnit.dispatch(['let', 'me', 'in']); // won't work dataUnit.dispatch('let me in'); // won't work dataUnit.dispatch(420); // won't work dataUnit.dispatch(null); // won't work dataUnit.dispatch(new Date()); // won't work dataUnit.dispatch(() => new Date()); // won't work 
Enter fullscreen mode Exit fullscreen mode

There are 5 other Units just like DictUnit in ActiveJS, ListUnit to store array, NumUnit to store number, StringUnit to store string, BoolUnit to store boolean, and GenericUnit to store anything.

Immutable

The immutable flag makes sure that the DictUnit doesn't let the value get mutated in any way. Let's try to mutate it anyway.

const newValue = {c: 3}; dataUnit.dispatch(newValue) // works, value is {c: 3} now  // try mutating the newValue newValue.c = 'hehe' // works, but dataUnit.value() // still {c: 3}  // let's try a different approach const currentValue = dataUnit.value() // {c: 3} currentValue.c = 'gotcha' // works, but dataUnit.value() // still {c: 3} 
Enter fullscreen mode Exit fullscreen mode

Persistent

The persistent flag makes the DictUnit persistent, such that whenever its value is updated, it saves that value to LocalStorage, so if we reinitialize a DictUnit with the same id and persistent: true flag, the DictUnit will restore its value from LocalStorage.

dataUnit.dispatch({c: 4}) // saved in LocalStorage  // after refreshing the browser-tab or reinitializing the DictUnit dataUnit.value() // {c: 4} // it restored the value from LocalStorage 
Enter fullscreen mode Exit fullscreen mode

Cache-Enabled

What if I told you that we can go back to all the previous values we just updated in previous examples, and then come back to the current value, yup Time-Travel is possible. All you need to provide is how many steps you want to be able to go back using the cacheSize option, by default it keeps 2 values and supports up to Infinity.

// let's reinitialize the Unit to demonstrate cache-navigation const dataUnit = new DictUnit({  cacheSize: Infinity, initialValue: {a: 1} }) // now let's dispatch a bunch of values to fill the cache dataUnit.dispatch({b: 2}) dataUnit.dispatch({c: 3}) dataUnit.dispatch({d: 4}) dataUnit.dispatch({e: 5})  // now the value is {e: 5}, and // the cache looks like this [{a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}]  // go back 1 step dataUnit.goBack() // now value is {d: 4}  // go back 2 steps dataUnit.jump(-2) // negative means back, positive means forward // now value is {b: 2}  // jump to the last value in cache dataUnit.jumpToEnd() // now value is {e: 5}  // jump to the first value in cache dataUnit.jumpToStart() // now value is {a: 1}  // go forward 1 step dataUnit.goForward() // now value is {b: 2} 
Enter fullscreen mode Exit fullscreen mode

That's it, folks, all done.

There are still a few things that we haven't covered that DictUnit can do, and we also haven't covered things like managing asynchronous API calls. But maybe that's a topic for the next article.

In the meantime, stay safe, try to have fun, and head over to ActiveJS website or documentation to learn more about how it can help you manage state with minimum effort.

Here's the StackBlitz playground link if you want to try it out yourself.

Here's a link to the visual playground, which you can try out without writing any code.

Also, I forgot to tell you that this is my first ever article on any platform, please let me know if I did an okay job, or if there's something that I can improve.

Cheers

🌏 ActiveJS Website
📖 ActiveJS Documentation
🤾‍♂️ ActiveJS Playground
💻 ActiveJS GitHub Repo (drop a ⭐ maybe 🙂

Next Read: Asynchronous State Management with ActiveJS

javascriptproductivitytypescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.