REACT Flashcards
What is Redux
Redux is a pattern and library that helps to managing and updating state in an application using events called “actions’. It is an open sours JS library for managing state in an application. It stores all necessary data in our application in a JS object separate from our application. We can grab this data for any component by connecting the component.
What is the Basic Idea Behind Redux
a single centralized place to contain global state in your application and specific patterns to follow when updating the state to make the code predictable.
State
Source of truth that drives our app
Actions
the events that occur in the app based on user input, and trigger updates in the state.
One-way data flow
- State describes condition of app at point in time
2. UI is revered based on that state Something happens (click) the state is updated based on what occurred
- The UI re-renders based on the new state
Immutability
can never be changed, in order to update code must make copies of existing obj/arrays and then modify the copies.
Actions
plain JS object that has a type field. (Event that describes something that happened in the application) type field should be a string that gives this action a descriptive name. Can have other fields with additional info about what happened by convention, put that info in a field called payload.
Action Creators
a function that create and returns an action object. Typically use these so we don’t have to write the action object by hand every time.
Reducers
function that receives the current state and an action object, decides how to update the state if necessary and returns the new state: (state, action) => newState (like an event listener which handles events based on the received action (event) type) get name bc similar to the kind of callback function you pass to the Array.reduce() method.
Reducers Rules
- Only calculate the new state value based on the state and action arguments
2. Not allowed to modify existing state, instead make immutable updates, by copying the existing state and making changes to the copied values.
3. Must not do any async logic, calculate random values, or cause side effects.
Reducer Flow
Check to see if reducer cares about this actions
If os make a copy of the state, update the copy with new values and return it
If not return the existing state unchanged.
Store
redux application state lives in an object called the store
created by passing in a reducer and has a method called get State that returned the current state value
dispatch
redux store has a method called dispatch. Only way to update the state is to call store.dispatch() and pass in an action object. The store will run its reducer function and save the new state value inside and we can gall get State() to retrace the updated value.
what are dispatching actions like
“triggering an event” in the application something happened and we want the store to know about it.
reducers act like …
act like event listeners and when they hear an action they are interested in they update the state in response.
when do we call action creators
We typically call action creators to dispatch the right action
one way data flow initial set up
Initial set up :
Redux store is created using a root reducer function
Store calls the root reducer once and saves the return value as its initial state
When the UI is first rendered, UI components access the current state of the Redux store, and use that data to decide what to render. They also subscribe to any future store updates so they can know if the state has changed.
one way data flow updates
Updates:
Something happens in the app, click
App code dispatches and action to the Redux store like: dispatch ({type: ‘counter/increment’})
Store runs the reducer function again with the previous state and the current action and saves the return value as the new state
The store notifies all parts of the UI that are subscribed that the store has been updated
Each ui components that needs data from the store checks to see if the parts of the state they need have changed.
Each component that sees its Datta has changed forces a serenader with the new data, so it can update what’s shown on the screen.
Flow
When something happens in the app:
The UI dispatches an action
The store runs the reducers, and the state is updated based on what occurred
The store notifies the UI that the state has changed
The UI re-renders based on the new state
Thunk
is a specific kind of Redux function that can contain async logic
thunks written in two functions
An inside thunk function which gets dispatch and getState as arguments
The outside creator function which creates and returns the thunk function
Using thunk requires that redux-thunk middleware be added to redux store when its created
When you need to make Ajax calls to fetch data from the server, you can put that call in a thunk.
Provider
We use Provider to pass down redux store behind the scenes so components can access it.
We wrap app and then pass store ={store} in the provider, now react components can use dispatch
Thunk middleware added
Once thunk middleware added to redux store it allows you to pass thunk functions directly to store.dispatch. a thunk function will always be called with (dispatch, getState) as its arguments and you can use them inside the thunk as needed. Thunks typically dispatch plain actions using action creators.
Data fetching for redux typically follows a predictable pattern:
A “start” action is dispatched before the request, to indicate that the request is in progress. This may be used to track loading state to allow skipping duplicate requests or show loading indicators in the UI.
The async request is made
Depending on the request result, the async logic dispatches either a “success” action containing the result data, or a “failure” action containing error details. The reducer logic clears the loading state in both cases, and either processes the result data from the success case, or stores the error value for potential display.
mapStateToProps
no longer reference store to get an updated state. adds new props to components we pass connect function, mapStateToProps and action creator as the props. when connect executes it calls the function passed in as a first argument, passing in the current state to the function.
mapDispatchTo props
second function passed in. it passes in the dispatch function.
const mapDispatchToProps = dispatch => { return { addItem: () => { dispatch(addItem()) } } }
we are adding a prop that points to a value addItem that points to the value, a function.
const mapDispatchToProps = dispatch => { return { getTrailsBoundToDispatch: () => dispatch(getTrails()) } }
export default connect(mapStateToProps, mapDispatchToProps)(Trails);
export const getParks = () => { return (dispatch) => { dispatch({type: "LOADING_PARKS"}) fetch('http://localhost:3001/parks') .then(res => res.json()) .then(parks => dispatch({type: "FETCH_PARKS", payload: parks})) } }
Write an action object, creator function we need this object to give to the reducer.
Only job to do is return dispatch(thunk)beginning of async. “hey i started”
second dispatch “hey im done”. sending in object to second one LOADING_Parks. (Kick off one)
go to reducer add case to switch.
go to component import dispatch getParks, connect. now connected to both state and dispatch.
ability to go get hem write a fetch.
1st calling dispatch LOADING_PARKS
fetch
.then res res.json
.then take in response park dispatch again passing in object, type: Fetch_Parks, second thing handing in action (payload: parks is the value)
have return of dispatch - function then dispatching when that function fired off which is fetching
returning a function, function taking in dispatch and calling it and the .then again is calling dispatch.
then add type to cases
case "LOADING_PARKS": return { ...state, loading: true }
case "FETCH_PARKS": return { ...state, parks: action.payload, loading: false }
case "ADD_PARK": return { ...state, loading: true }
case 'PARK_ADDED': return { ...state, parks: [...state.parks, action.payload], loading: false }
case statement, loading parks. return, nothing new …state. first is just returning beginning of state.
FETCH_PARKS return all state, and parks as a key with value of action.payload
of parks
ParkList.js
in MSTP add, numParks: state.parkReducer.parks.length
<h2> number of parks { this.props.numParks </h2>
of trails
TrailList.js
in MSTP add, numTrails: state.trailReducer.parks.length
<h2> number of trails {this.props.numTrails</h2>
Filter array of Objects
declare what value to filter on and then map the filtered objects.
<div> {trails.filter(trail => trail.difficulty = easy).map(filteredTrail => ( <li> {filteredTrail.name} </li> ))} </div>
arrow function
prevents this bugs
display items
less expensive
client side routing
we are not making constant http get requests it is responsibility of the client side code rather than server to handle routing fetching and displaying of data in browser. major benefit is speed. we get one original get request with our initial html css and js files. with js history api we have ability to push state to history entries state/title/url