redux.md 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
Use of redux
======


?> `Redux` is a predictable state container for JavaScript apps.


Why redux?


As you may now, react components have a strict living period and as soon as they are *unmounted* from the DOM the data they contained in their state is completely deleted. The redux object (called a *store*) on the other hand will live as long as your app is open in the browser so it’s a nice place to store information in.


*NB: it lives as long as your browser is open because it usually is the root component of your react app, as you can see in `frontend/src/index.js`*.


Redux solves another issue which is that sometimes different components in different locations of your *virtual DOM* need to access similar data. So redux is very useful to store data from a backend API.



## How it works


To understand how redux works, you need to understand 2 principles: *actions* and *reducers*.


!> *Actions* are objects/functions your app *dispatches* and that contains a `type` (to identify the action) and some optional contextual data.


!> *Reducers* are objects/functions that listen to the *actions* being dispatched and update the redux `store`'s **state** depending on the action and the contextual data they provide.



### Example of an action


*Taken from `frontend/src/redux/actions/map.js`.*


```js
export function saveMainMapStatus(newStatus) {
  return {
    type: SAVE_MAIN_MAP_STATUS,
    newStatus
  };
```


This action is of type `SAVE_MAIN_MAP_STATUS` (defined in `frontend/src/redux/actions/action-types.js`) and is called with a *new status* (a javascript Object) as contextual data.
This action is used to save the state of the map (what is the zoom level, what are the coordinates of the center and what layer is selected) in our application.



### Example of a reducer


To interpret this action when it is *dispatched* we have the following *reducer*:


```js
export function saveMainMapStatus(state = { center: [0, 2], zoom: 2, selectedLayer: "OpenStreetMap France" }, action) {
  switch (action.type) {
    case SAVE_MAIN_MAP_STATUS:
      return {
        center: action.newStatus.center,
        zoom: action.newStatus.zoom,
        selectedLayer: action.newStatus.selectedLayer
      };


    default:
      return state;
  }
}
```


So a *reducer* is given the previous state of the redux *store* (or here a portion of the store, this will be explained later) and an *action*. If the action "concerns" the reducer then it returns a new state based on the action contextual data; otherwise, the state is returned unchanged.


The idea is that we have tons of reducers in our app, and we compose them to have a better organization. So each of those reducers will be called for all dispatched actions, hence the simple `switch` statement to check if this reducer is concerned by the action.




### General shape of our app's redux store


In *REX-DRI*, all the reducers are composed in such a way that the final store looks like this:


```js
{
    app: {
        // data that concerns the app and only the app
    },
    api: {
        // data that concerns all the endPoint provided by the backend API
    }
}
```


The data in `app` is build with reducers handwritten, just like the one above. The data in `api` is based on reducers generated automatically at runtime based on the app [config files](Application/Backend/config_files.md).



## Accessing the data in the redux store


### Direct access


A direct access to the redux store is possible and very simple: you need to call the `getState` method on the store defined in `frontend/src/redux/store.js`. `getState` returns the full current state of your store.


```js
import store from "../store";
const myData = store.getState().app.//....
```


?> :information_desk_person: some helpers functions have been built in `frontend/src/redux/api/utils.js` to handle this access more easily in some circumstances.



Such a direct access is, however, not always interesting...



### Subscribing to the store


Redux make it possible to make a component subscribe to the store or a portion of it, and when it's modified, then your component will be automatically updated. When we say "subscribe" we mean that:


- Redux will add the `props` you tell him to your components,
- Those props map to a portion of the redux store (/state),
- Every time that portion of the store is updated, the props on your components will be updated,
- And finally, given how react is built and because your props have been updated, your component will be updated. :confetti_ball:


Here is an implementation example:


```js
import React, { Component } from "react";
import { connect } from "react-redux";

class UnivMap extends Component {
    render(){
        return (<>{this.props.map}</>)
    }
}

const mapStateToProps = (state) => {
  return {
    map: state.app.mainMap
  };
};

export default connect(mapStateToProps)(UnivMap);
```


When exporting your component, you wrap it with the `connect` function provided by redux. This function takes as argument another `mapStateToProps` function.


`mapStateToProps` is a function that takes as argument the state (of the redux store) and returns an object with key(s) the `props` that will be added to your component and value(s) the portion(s) of the store you are interested in (and that will be accessible from the `props`).


And then everything is automated! :confetti_ball:



## Putting data in the store


Well, it's nice to be able to read data from the redux store, but it would be even cooler to be able to put data in the store.


There comes in the actions (and indirectly the reducers) you have defined earlier :smile:.


The idea is that you want your component to be able to *dispatch* actions (that will be handled by the reducers and that will update the state of the redux store).
This is done once again with redux `connect` function:



```js
import React, { Component } from "react";
import { connect } from "react-redux";
import { saveMainMapStatus } from "../../redux/actions/map";



class UnivMap extends Component {
  componentWillUnmount() {
    // ...
    this.props.saveMainMap({
      zoom: leafletInstance.getZoom(),
      center,
      selectedLayer
    });
    // ...
  }

  render() {
    return (<> />)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    saveMainMap: (mapState) => dispatch(saveMainMapStatus(mapState)),
  };
};

export default connect(() => {}, mapDispatchToProps)(UnivMap);
```


So this time, we have the `mapDispatchToProps` function to pass to the `connect` function from redux.


`mapDispatchToProps` takes as argument the *dispatch* capability provided by redux and returns an object. Once again, the key(s) of this object will be mapped to your component's `props`. Those new `props` will be functions that take optional arguments and then *dispatch* a specific action.


That's all! :confetti_ball:


?> :information_desk_person: as you can see the `connect` function from redux takes as first argument a `mapStateToProps` function and as second argument a `mapDispatchToProps` function. Providing the second one is optional. To provide only the second one, you can put `() => {}` (useless function) as first argument.




## Redux and the backend API


!> :warning: This section if probably the most important if you are already familiar with redux. Because we have tons of backend API endpoints, we have implemented a generic way to use them with redux. :warning:



### Dynamic actions and reducers




As you can see above, writing actions and reducers is very verbose and redundant, especially if you have a lot of them that only differ from a name or endpoint.


So... actions related to the API are generated at runtime based on the [configuration]((Application/Backend/config_files.md)) of all available endpoints. The same goes for the associated *reducers* that are then combined under `state.api` in the redux store. :confetti_ball:


Since those actions are generated dynamically, they are not available while coding. To use those actions you need to use the `getActions` helper from `frontend/src/redux/api/getActions.js`. This function takes as parameter the endpoint you want to fetch or write to, and returns an object with different possible actions. Here is an example:



```js
import getActions from "../../redux/api/getActions";

// ........

const mapDispatchToProps = (dispatch) => {
  return {
    api: {
      universities: () => dispatch(getActions("universities").readAll()),
      mainCampuses: () => dispatch(getActions("mainCampuses").readAll()),
      cities: () => dispatch(getActions("cities").readAll()),
      countries: () => dispatch(getActions("countries").readAll())
    }
  };
};

// ......
```


*NB: more on why we put it inside `api` in the next section.*


Depending on the viewset/endpoint configuration, the `getActions` function will give you access to some or all of the following functions:


- `readAll()`: reads all the data from the endpoint (data will be given as an array of object)
- `readSpecific(id)`: reads the data for an instance (the `id` is the instance's `id`/primary key) (data will be returned as an object)
- `create(data)`: creates an object on the endpoint with attributes values given by `data`.
- `update(data)` (`data` must have an `id` field): updates the instance identified by `id`.
- `setInvalidatedAll()`: invalidates "all" the data for the endpoint,
- `setInvalidatedSpecific()`: invalidates "specific" data from the endpoint.


?> :information_desk_person: invalidating data will usually trigger a refresh of that data with a new API call.


?> Do you recall that an update to the redux store will be propagated to the components that imported that portion of the store (concerned by the update). So they will be updated on their own every time new data comes in, like magic! :confetti_ball:


!> If a viewset is *configured* with endpoint `universities` in the config file, then in `getActions` you will have access to it by specifying that exact endpoint, ie `getActions("universities")`.



!> `...Specific` and `...All` are stored in distinct location in the the redux store.



### Conventions for reading data


If you are familiar with network request, you will know that those are "async", and that they can go through different states: from `reading` to `readSucceeded` or `readFailed` for instance. We need to keep track of those state so that the UI is coherent and let the user know what is the current state. Therefore, all those different states are stored for all possible actions (and for all possible endpoints) in... the redux store :confetti_ball:.


As a result, the real data returned by the endpoint will usually be stored under `...Succeeded.data` state portion.



To handle all those specific behaviours and easily use the data from the backend API (stored in the redux store under nasty path), a nice class has been designed: `CustomComponentForAPI`. It inherits from `React.Component` and you can use it as a standard component, except that you must call the `customRender` function and not the `render` function you are used to with standard react components.


?> :information_desk_person: You should use this class only if you need to fetch data from the frontend.



The `CustomComponentForAPI` class provides nice functions to access the data. For instance, `getLatestReadData(propName)` will return the latest data read for a `prop` (mapped by redux `connect` with `mapStateToProps`) identified by `propName` (ie: the *key* of the `prop`). You should look at all the other functions available in this class :wink:.



For the `CustomComponentForAPI` to work properly, i.e. for it to fetch the needed data, display loading indicator and retrieve the data quickly you need to follow this convention:



```js
const mapStateToProps = (state) => {
  return {
    propName: state.api.whateverAll // or whateverSpecific
  };
};


const mapDispatchToProps = (dispatch) => {
  return {
    api: {
      propName: () => dispatch(getActions(//...
    }
  };
};
```
!> **In `mapStateToProps`, for the `props` that will correspond to data fetched from the API, you must not go in the details of the state: we need to have access to `isReadingAll`, etc.**



!> **The function that will be used to dispatch the action associated with fetching the data for `propName` must be identified by `api.propName` in the `mapDispatchToProps` function.**



 That's all :confetti_ball:.



### Words on updating data on the API


TODO



### Troubleshooting


- Open your console and look at the actions and resulting states that are being logged: explore.


- As explained earlier, the values from the api get be read either for "all" or a "specific" instance. So you need to specify the one you are interested in when getting the action (eg: `.readAll` or `.readSpecific`) and you need to specify the matching one you are retrieving from the redux state: `state.api.whateverAll` or `state.api.whateverSpecific`.


### Under the hood


You can look at the files in `frontend/src/redux/api` to know more about how all of this works.