Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux for maintaining only shared data

In our Angular app, we are planning to use Redux but decided that we will use it for managing only the data that are shared by at-least two components. The data that are used by only one component will be directly fetched without using Redux. For e.g. assume that a component has to display a list of values and these values are not shared with any other component then we will fetch this list using service. But while fetching this data it may affect some other state in the store, like it may dispatch some action like NETWORK_REQUEST_SENT, NETWORK_REQUEST_COMPLETED, so that a spinner/overlay component can change its display.

Now the question is which part of the code should be responsible for dispatching these actions.

  • Scenario 1 : The container component that fetches the data from the service could dispatch these actions, but I don't think it belongs here.
  • Scenario 2 : The service which makes the HTTP call could dispatch these action, then that means the service has to subscribe to the HTTP observable and return its own observable for the component.
  • Scenario 3 : Could do it in a Redux middleware, but then we have to dispatch an action for fetching the list of values and that means the list of values has to be stored in the store, that we don't want.
  • Scenario 4 : As mentioned here, we could create an abstraction layer but then it feels like there is no need for middleware then.
like image 456
wolverine Avatar asked Nov 10 '17 04:11

wolverine


People also ask

When should I not use Redux?

As a rule of thumb - and one shared by one of Redux's creators, Dan Abramov - you don't need to use Redux unless you're unable to manage state within React or other front-end frameworks you're working with.

Can we store data in Redux?

Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer. A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app.

What data should be stored in Redux?

There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.


1 Answers

If you are using HttpClientModule you can register an interceptor, like explained in https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

You can invoke NETWORK_REQUEST_SENT when it is invoked and NETWORK_REQUEST_COMPLETED in finally to invoke an action when the request completes. Then there is no need to have another observable.

like image 159
Günter Zöchbauer Avatar answered Oct 06 '22 06:10

Günter Zöchbauer