loading redux items into state from a direct link

Viewed 79

This is sort of a "best practices" question, since I'm not clear on the right way to handle this case.

The situation is that I have a bookstore app with a list of books that exists as state.bookstore.books. When the visitor loads the index page of the bookstore, a thunk action is dispatched that loads all the book objects in the user's collection into the state.bookstore.books array.

From the bookstore page, a user can click on an individual book, and a new page is loaded that pulls the book item from the state books array and displays the details.

My problem is that if a user directly visits the book detail link (eg. "mysite.com/book/123") without first going through the homepage, the state.bookstore.books array is empty, and the page has no data to display.

My question is what is the "right" way to do this? Would I dispatch the loadBookstore action to populate the state anytime the app is initialized? Would I create a new redux feature for book? Would I ignore looking up the book in the state, and just grab the specific book record from the server?

I am assuming that I'm doing it wrong / implementing an anti-pattern because selectors are not built to take parameters, so it seems like since there's no easy way to grab book 123 from the store, then I shouldn't be doing it this way.

1 Answers

Let's say we have 2 components

  1. BooksHome for /books/
  2. SingleBook for /books/:id

So when the user visits /books/ route, fire a thunk fetchBooks(..) which loads books and saves them in state.bookstore.books and display those books in BooksHome

And when the user visits /books/:id route, fire a thunk fetchSingleBook(..) which will find book item with :id in state.bookstore.books if that's present return it and display it in SingleBook and if it's not there, fetch it, add it to state.bookstore.books and return it and display it in SingleBook.

Explanation:

When the user visits /books/123 right away, state.bookstore.books is [] so no item is found, so we'll fetch it, store it and display it.

When the user visits /books/ (data fetched and stored) and then visits /books/123, state.bookstore.books is having an item with id:123 so the item is found, so we'll get it from state.bookstore.books and display it.

Must do things:

  1. fetchBooks must be dispatched in BooksHome but not in App
  2. Same way fetchSingleBook must be dispatched in SingleBook

Things optimised with this approach:

  1. We need not fetch all books for displaying a single book.
  2. We need not re-fetch book's data when it is already available in state.bookstore.books

Hope this helps

Related