Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a better way to handle nested properties in state? #37

Closed
AxelMarquez opened this issue Apr 13, 2018 · 4 comments
Closed

Is there a better way to handle nested properties in state? #37

AxelMarquez opened this issue Apr 13, 2018 · 4 comments

Comments

@AxelMarquez
Copy link

For example, I have the following nested state (only left the relevant parts for clarity):

class AppState {

   final OpenBook openBook;
}

class OpenBook {

  final bool headerIsFetching;
}

 
And the reducer:

new AppState(

  openBook: new OpenBook(//<- This can be optimized! new instance is built for every cycle regardless of the action
    headerIsFetching: buildFetchingReducer<FetchOpenBookHeaderAction, FetchOpenBookHeaderSucceededAction, FetchOpenBookHeaderFailedAction>(state.openBook.headerFetching, action)
  )  
);

 
I have thought 2 options:

  1. Encapsulate the instantiation of the OpenBook inside an if that tests for the relevant actions, but this leads to code duplication and it goes against the Open/closed principle (SOLID)
  2. Use a switch and for each relevant action create a new OpenBook and initialize only the relevant property, but it feels weird as Dart doesn't have the Spread operator (the three dots in javascript)
  3. Flatten the state

Do you have a recommendation?

@brianegan
Copy link
Owner

brianegan commented Apr 19, 2018

Heya, sorry about the delay -- somehow missed this notification! Have you played around with the combineReducers + TypedReducer stuff at all? https://github.com/johnpryan/redux.dart/blob/master/doc/combine_reducers.md

That, in combination with something like a copyWith method to emulate the spread operator in a type-safe way might help out here. (https://github.com/brianegan/flutter_architecture_samples/blob/master/example/redux/lib/models/app_state.dart#L23)?

That would allow you to handle the actions you care about without creating a new instance each time unless it needs to change.

@brianegan
Copy link
Owner

Hey, please let me know if I can help further or if it's cool to go ahead and close this down :) Best, Brian.

@AxelMarquez
Copy link
Author

Hello Brian! Sorry for my late reply,

Many thanks for the hints! I ended up using copyWith and really liked how clear the code looks with this method. Feel free to close this.

Again many thanks, and awesome library! 😊

@brianegan
Copy link
Owner

Sure thing, glad to help, and happy it's working well for ya :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants