andrewngu/sound-redux

Query on reducer/store structure

ryannealmes opened this issue · 3 comments

How do you decide whether or not to nest data in your store. For example you have a player that stores information like the song that's currently playing, current time, selected playlist.

This makes sense, but from pretty much everything I have read and listened to, you should keep your data as flat as possible. You could have rather had currentSongIndex at the top level instead of nested within player.

Note I am not saying you are wrong, quite the opposite :), just trying to understand your thought process for stopping yourself from nesting stuff any further.

Would it be fair to say that you store any data from the server in entities (domain data) and any other data related to app state or ui state grouped at the root level?

Thanks!

Keeping your data flat makes sense for trivial example projects, but not for bigger projects. It seems unreasonable to have a reducer file for every variable in your application state. It's more practical to group related data, not only because mental model of your application easier to reason about, but because there are actions that might update multiple parts of your reducer.

For example, you might keep username and userId in your user reducer and on a logout action you might set both of those to null. Keeping a separate reducer for both username and userId would result in you writing more code. Also, what are you really sacrificing here?

const { username, userId } = this.props.user
vs.
const { username, userId } = this.props;

I think the argument of keeping your data flat, refers to the state object in the reducer. Which I generally agree with. IE, in regards to player, means keeping this object flat:

const initialState = {
  currentSongIndex: null,
  currentTime: 0,
  isPlaying: false,
  selectedPlaylists: [],
};

To answer your question about the use of server data as entities. That is definitely not a hard and fast rule. You should place objects in entities if they are things that might appear in more than one place.

For example, the same song might appear in multiple playlists or even a search query. A user might be the author of multiple songs or make multiple comments.

An example of server data that wouldn't belong in the entities object, would be a chat message. If you had a chatroom application, you wouldn't expect to see the same chat message appear in multiple rooms. (You could certainly see the same text, but the messages id would always be unique). I might be inclined to keep the messages as an array of objects.

Great this write up makes sense. I guess I just need more practice with it :)

Thanks again. Your repo is super helpful to everyone. Haha must be fun to code in react/redux on a music player you wrote yourself in react/redux.