Kā es veidoju vienas lapas React lietojumprogrammu

Ar datu struktūrām, komponentiem un integrāciju ar Redux

Nesen es izveidoju vienas lapas lietojumprogrammu, kas mijiedarbojas ar aizmugurējo JSON API serveri. Es izvēlējos izmantot React, lai padziļinātu izpratni par React pamatiem un to, kā katrs rīks var palīdzēt, veidojot mērogojamu priekšgalu.

Šīs lietojumprogrammas kaudze sastāv no:

  • Frontend ar React / Redux
  • Aizmugurējais JSON API serveris ar Sinatra, integrēts ar Postgres datu bāzes noturībai
  • API klients, kas ienes datus no OMDb API, rakstīts rubīnā

Pieņemsim, ka šai ziņai ir pabeigta aizmugure. Tāpēc pievērsīsimies tam, kā dizaina lēmumi tiek pieņemti priekšējā daļā.

Papildu piezīme: šeit sniegtie lēmumi ir tikai atsauces nolūkā un var atšķirties atkarībā no jūsu pieteikuma vajadzībām. Demonstrēšanai šeit tiek izmantots OMDb Movie Tracker piemērs.

Lietotne

Pieteikums sastāv no meklēšanas ievades formas. Lietotājs var ievadīt filmas nosaukumu, lai atgrieztu filmas rezultātu no OMDb. Lietotājs var arī saglabāt izlases sarakstā filmu ar vērtējumu un īsiem komentāriem.

Lai apskatītu pēdējo lietotni, noklikšķiniet šeit. Lai skatītu pirmkodu, noklikšķiniet šeit.

Kad lietotājs sākumlapā meklē filmu, tas izskatās šādi:

Vienkāršības labad šajā rakstā mēs koncentrēsimies tikai uz lietojumprogrammas galveno funkciju izstrādi. Varat arī pāriet uz II daļu: Reduksssērijas.

Datu struktūra

Piemērotu datu struktūru noteikšanai vajadzētu būt vienam no vissvarīgākajiem lietotnes izstrādes aspektiem. Tam vajadzētu būt pirmajam solim, jo ​​tas nosaka ne tikai to, kā priekšpusei vajadzētu atveidot elementus, bet arī to, kā API serverim jāatdod JSON atbildes.

Šai lietotnei mums būs nepieciešamas divas galvenās informācijas daļas, lai pareizi renderētu mūsu lietotāja saskarni: viens filmas rezultāts un izlases filmu saraksts .

Filmas rezultātu objekts

Viena filmas rezultāts saturēs tādu informāciju kā nosaukums, gads, apraksts un plakāta attēls. Tādējādi mums ir jādefinē objekts, kas var saglabāt šos atribūtus:

{ "title": "Star Wars: Episode IV - A New Hope", "year": "1977", "plot": "Luke Skywalker joins forces with a Jedi Knight...", "poster": "//m.media-amazon.com/path/to/poster.jpg", "imdbID": "tt0076759"}

posterĪpašums ir vienkārši URL plakāta attēlu, kas tiks parādīts rezultātos. Ja šai filmai nav pieejams plakāts, tas būs “N / A”, kuru mēs parādīsim ar vietturi. Mums būs nepieciešams arī imdbIDatribūts, lai unikāli identificētu katru filmu. Tas ir noderīgi, lai noteiktu, vai filmas rezultāts jau ir iekļauts izlases sarakstā. Mēs vēlāk izpētīsim, kā tas darbojas.

Izlases saraksts

Izlases sarakstā būs visas filmas, kas saglabātas kā izlases. Saraksts izskatīsies apmēram šādi:

[ { title: "Star Wars", year: "1977", ..., rating: 4 }, { title: "Avatar", year: "2009", ..., rating: 5 }]

Paturiet prātā, ka mums no saraksta būs jāmeklē konkrēta filma, un šīs pieejas sarežģītība ir O (N) . Lai gan tas darbojas labi mazākām datu kopām, iedomājieties, ka jāmeklē filma izlases sarakstā, kas pieaug bezgalīgi.

Paturot to prātā, es izvēlējos ietvert jaucējgaldu ar taustiņiem imdbIDun vērtībām kā iecienītākajiem filmu objektiem:

{ tt0076759: { title: "Star Wars: Episode IV - A New Hope", year: "1977", plot: "...", poster: "...", rating: "4", comment: "May the force be with you!", }, tt0499549: { title: "Avatar", year: "2009", plot: "...", poster: "...", rating: "5", comment: "Favorite movie!", }}

Izmantojot šo, mēs varam meklēt filmu izlases sarakstā O (1) laikā pēc tās imdbID.

Piezīme: izpildlaika sarežģītībai, visticamāk, vairumā gadījumu nebūs nozīmes, jo klienta pusē datu kopas parasti ir mazas. Mēs tāpat gatavosim sagriezt un kopēt (arī O (N) darbības) Redux. Bet kā inženierim ir labi apzināties iespējamo optimizāciju, ko mēs varam veikt.

Komponenti

Komponenti ir React centrā. Mums būs jānosaka, kuri no tiem mijiedarbosies ar Redux veikalu un kuri ir paredzēti tikai prezentācijai. Mēs varam arī atkārtoti izmantot dažus prezentācijas komponentus. Mūsu komponentu hierarhija izskatīsies apmēram šādi:

Galvenā lapa

Mēs apzīmējam mūsu lietotnes komponentu augstākajā līmenī. Kad tiek apmeklēts saknes ceļš, tam ir jāatveido SearchContainer . Tam arī jāparāda zibatmiņas lietotājam un jāapstrādā klienta puses maršrutēšana.

SearchContainer atjaunos filmu rezultātu no mūsu Redux veikala, sniedzot informāciju par aksesuārus, lai MovieItem kausēšanai. Tas nosūtīs arī meklēšanas darbību, kad lietotājs iesniedz meklēšanu vietnē SearchInputForm . Vairāk par Reduksu vēlāk.

Veidlapa Pievienot izlasei

Kad lietotājs noklikšķina uz pogas “Pievienot izlasei”, mēs parādīsim kontrolēto komponentu AddFavoriteForm .

Mēs pastāvīgi atjauninām tā stāvokli ikreiz, kad lietotājs komentāra teksta apgabalā maina vērtējumu vai ievades tekstu. Tas ir noderīgi, lai apstiprinātu, iesniedzot veidlapu.

RatingForm atbild atveidei dzeltenām zvaigznēm, kad lietotājs noklikšķina uz tiem. Tas arī informē pašreizējo reitinga vērtību vietnē AddFavoriteForm .

Cilne Izlase

Kad lietotājs noklikšķina uz cilnes Izlase, lietotne renderē FavoritesContainer .

FavoritesContainer ir atbildīgs par izguvei izlases sarakstu no Redux veikalā. Tas nosūta arī darbības, kad lietotājs maina vērtējumu vai noklikšķina uz pogas “Noņemt”.

Our MovieItem and FavoritesInfo are simply presentational components that receive props from FavoritesContainer.

We’ll reuse the RatingForm component here. When a user clicks on a star in the RatingForm, the FavoritesContainer receives the rating value and dispatches an update rating action to the Redux store.

Redux Store

Our Redux store will include reducers that handle the search and favorites actions. Additionally, we’ll need to include a status reducer to track state changes when a user initiates an action. We’ll explore more on the status reducer later.

//store.js
import { createStore, combineReducers, applyMiddleware } from 'redux';import thunk from "redux-thunk";
import search from './reducers/searchReducer';import favorites from './reducers/favoritesReducer';import status from './reducers/statusReducer';
export default createStore( combineReducers({ search, favorites, status }), {}, applyMiddleware(thunk))

We’ll also apply the Redux Thunk middleware right away. We’ll go more into detail on that later. Now, let’s figure out how we manage the state changes when a user submits a search.

Search Reducer

When a user performs a search action, we want to update the store with a new search result via searchReducer. We can then render our components accordingly. The general flow of events looks like this:

We’ll treat “Get search result” as a black box for now. We’ll explore how that works later with Redux Thunk. Now, let’s implement the reducer function.

//searchReducer.js
const initialState = { "title": "", "year": "", "plot": "", "poster": "", "imdbID": "",}
export default (state = initialState, action) => { if (action.type === 'SEARCH_SUCCESS') { state = action.result; } return state;}

The initialState will represent the data structure defined earlier as a single movie result object. In the reducer function, we handle the action where a search is successful. If the action is triggered, we simply reassign the state to the new movie result object.

//searchActions.jsexport const searchSuccess = (result) => ({ type: 'SEARCH_SUCCESS', result});

We define an action called searchSuccess that takes in a single argument, the movie result object, and returns an action object of type “SEARCH_SUCCESS”. We will dispatch this action upon a successful search API call.

Redux Thunk: Search

Let’s explore how the “Get search result” from earlier works. First, we need to make a remote API call to our backend API server. When the request receives a successful JSON response, we’ll dispatch the searchSuccess action along with the payload to searchReducer.

Knowing that we’ll need to dispatch after an asynchronous call completes, we’ll make use of Redux Thunk. Thunk comes into play for making multiple dispatches or delaying a dispatch. With Thunk, our updated flow of events looks like this:

For this, we define a function that takes in a single argument title and serves as the initial search action. Thisfunction is responsible for fetching the search result and dispatching a searchSuccess action:

//searchActions.jsimport apiClient from '../apiClient';
...
export function search(title) { return (dispatch) => { apiClient.query(title) .then(response => { dispatch(searchSuccess(response.data)) }); }}

We’ve set up our API client beforehand, and you can read more about how I set up the API client here. The apiClient.query method simply performs an AJAX GET request to our backend server and returns a Promise with the response data.

We can then connect this function as an action dispatch to our SearchContainer component:

//SearchContainer.js
import React from 'react';import { connect } from 'react-redux';import { search } from '../actions/searchActions';
...
const mapStateToProps = (state) => ( { result: state.search, });
const mapDispatchToProps = (dispatch) => ( { search(title) { dispatch(search(title)) }, });
export default connect(mapStateToProps, mapDispatchToProps)(SearchContainer);

When a search request succeeds, our SearchContainer component will render the movie result:

Handling Other Search Statuses

Now we have our search action working properly and connected to our SearchContainer component, we’d like to handle other cases other than a successful search.

Search request pending

When a user submits a search, we’ll display a loading animation to indicate that the search request is pending:

Search request succeeds

If the search fails, we’ll display an appropriate error message to the user. This is useful to provide some context. A search failure could happen in cases where a movie title is not available, or our server is experiencing issues communicating with the OMDb API.

To handle different search statuses, we’ll need a way to store and update the current status along with any error messages.

Status Reducer

The statusReducer is responsible for tracking state changes whenever a user performs an action. The current state of an action can be represented by one of the three “statuses”:

  • Pending (when a user first initiates the action)
  • Success (when a request returns a successful response)
  • Error (when a request returns an error response)

With these statuses in place, we can render different UIs based on the current status of a given action type. In this case, we’ll focus on tracking the status of the search action.

We’ll start by implementing the statusReducer. For the initial state, we need to track the current search status and any errors:

// statusReducer.jsconst initialState = { search: '', // status of the current search searchError: '', // error message when a search fails}

Next, we need to define the reducer function. Whenever our SearchContainer dispatches a “SEARCH_[STATUS]” action, we will update the store by replacing the search and searchError properties.

// statusReducer.js
...
export default (state = initialState, action) => { const actionHandlers = { 'SEARCH_REQUEST': { search: 'PENDING', searchError: '', }, 'SEARCH_SUCCESS': { search: 'SUCCESS', searchError: '', }, 'SEARCH_FAILURE': { search: 'ERROR', searchError: action.error, }, } const propsToUpdate = actionHandlers[action.type]; state = Object.assign({}, state, propsToUpdate); return state;}

We use an actionHandlers hash table here since we are only replacing the state’s properties. Furthermore, it improves readability more than using if/else or case statements.

With our statusReducer in place, we can render the UI based on different search statuses. We will update our flow of events to this:

We now have additional searchRequest and searchFailure actions available to dispatch to the store:

//searchActions.js
export const searchRequest = () => ({ type: 'SEARCH_REQUEST'});
export const searchFailure = (error) => ({ type: 'SEARCH_FAILURE', error});

To update our search action, we will dispatch searchRequest immediately and will dispatch searchSuccess or searchFailure based on the eventual success or failure of the Promise returned by Axios:

//searchActions.js
...
export function search(title) { return (dispatch) => { dispatch(searchRequest());
apiClient.query(title) .then(response => { dispatch(searchSuccess(response.data)) }) .catch(error => { dispatch(searchFailure(error.response.data)) }); }}

We can now connect the search status state to our SearchContainer, passing it as a prop. Whenever our store receives the state changes, our SearchContainer renders a loading animation, an error message, or the search result:

//SearchContainer.js
...(imports omitted)
const SearchContainer = (props) => (   props.search(title) } /> { (props.searchStatus === 'SUCCESS') ?  : null } { (props.searchStatus === 'PENDING') ?    : null } { (props.searchStatus === 'ERROR') ?  

{ props.searchError }

: null } );
const mapStateToProps = (state) => ( { searchStatus: state.status.search, searchError: state.status.searchError, result: state.search, });
...

Favorites Reducer

We’ll need to handle CRUD actions performed by a user on the favorites list. Recalling from our API endpoints earlier, we’d like to allow users to perform the following actions and update our store accordingly:

  • Save a movie into the favorites list
  • Retrieve all favorited movies
  • Update a favorite’s rating
  • Delete a movie from the favorites list

To ensure that the reducer function is pure, we simply copy the old state into a new object together with any new properties usingObject.assign. Note that we only handle actions with types of _SUCCESS:

//favoritesReducer.js
export default (state = {}, action) => { switch (action.type) { case 'SAVE_FAVORITE_SUCCESS': state = Object.assign({}, state, action.favorite); break;
case 'GET_FAVORITES_SUCCESS': state = action.favorites; break;
case 'UPDATE_RATING_SUCCESS': state = Object.assign({}, state, action.favorite); break;
case 'DELETE_FAVORITE_SUCCESS': state = Object.assign({}, state); delete state[action.imdbID]; break;
default: return state; } return state;}

We’ll leave the initialState as an empty object. The reason is that if our initialState contains placeholder movie items, our app will render them immediately before waiting for the actual favorites list response from our backend API server.

From now on, each of the favorites action will follow a general flow of events illustrated below. The pattern is similar to the search action in the previous section, except right now we’ll skip handling any “PENDING” status.

Save Favorites Action

Take the save favorites action for example. The function makes an API call to with our apiClient and dispatches either a saveFavoriteSuccess or a saveFavoriteFailure action, depending on whether or not we receive a successful response:

//favoritesActions.jsimport apiClient from '../apiClient';
export const saveFavoriteSuccess = (favorite) => ({ type: 'SAVE_FAVORITE_SUCCESS', favorite});
export const saveFavoriteFailure = (error) => ({ type: 'SAVE_FAVORITE_FAILURE', error});
export function save(movie) { return (dispatch) => { apiClient.saveFavorite(movie) .then(res => { dispatch(saveFavoriteSuccess(res.data)) }) .catch(err => { dispatch(saveFavoriteFailure(err.response.data)) }); }}

We can now connect the save favorite action to AddFavoriteForm through React Redux.

To read more about how I handled the flow to display flash messages, click here.

Conclusion

Designing the frontend of an application requires some forethought, even when using a popular JavaScript library such as React. By thinking about how the data structures, components, APIs, and state management work as a whole, we can better anticipate edge cases and effectively fix errors when they arise. By using certain design patterns such as controlled components, Redux, and handling AJAX workflow using Thunk, we can streamline managing the flow of providing UI feedback to user actions. Ultimately, how we approach the design will have an impact on usability, clarity, and future scalability.

References

Fullstack React: The Complete Guide to ReactJS and Friends

About me

Es esmu programmatūras inženieris, kas atrodas Ņujorkā un ir SpaceCraft līdzautors. Man ir pieredze vienas lapas lietojumprogrammu projektēšanā, stāvokļa sinhronizācijā starp vairākiem klientiem un mērogojamu lietojumprogrammu izvietošanā ar Docker.

Pašlaik meklēju savu nākamo pilna laika iespēju! Lūdzu, sazinieties, ja domājat, ka es labi iederēšos jūsu komandā.