ReactRouter-Redux-API
ReactRouter-Redux-API
One of the main features of React is that it allows the creation of single-
page applications (SPAs) that are rendered on the client's side. An SPA
might have multiple views (aka pages), and unlike the conventional
multi-page apps, navigating through these views should not result in the
entire page being reloaded. Instead, we want the views to be rendered
inline within the current page. The end user, who’s accustomed to multi-
page apps, expects the following features to be present in an SPA:
Routing is the process of keeping the browser URL in sync with what’s
being rendered on the page. React Router lets you handle
routing declaratively. The declarative routing approach allows you to
control the data flow in your application, by saying “the route should look
like this”:
<Route path="/about" component={About}/>
You can place your <Route> component anywhere that you want your
route to be rendered. Since <Route>, <Link> and all the other React
Router API that we’ll be dealing with are just components, you can easily
get used to routing in React.
In this Super Skill, we'll cover four main topics. First, we’ll be setting up
React and React Router using npm. Then we’ll jump right into React
Router basics. You’ll find different code demonstrations of React Router in
action. The examples covered include:
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
</Router>
Router
You need a router component and several route components to set up a
basic route as exemplified in the previous screen. Since we’re building a
browser-based application, we can use two types of routers from the React
Router API:
1. <BrowserRouter>
2. <HashRouter>
The primary difference between them is evident in the URLs that they
create:
// <BrowserRouter>
http://example.com/about
// <HashRouter>
http://example.com/#/about
Router
The <BrowserRouter> is more popular amongst the two because it uses the
HTML5 History API to keep track of your router history. The <HashRouter>,
on the other hand, uses the hash portion of the URL ( window.location.hash)
to remember things. If you intend to support legacy browsers, you should
stick with <HashRouter>.
In index.js:
/* Import statements */
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
Note: A router component can only have one single child element. The
child element can be an HTML element — such as div — or a react
component.
For the React Router to work, you need to import the relevant API from
the react-router-dom library. Here We’ve imported
the BrowserRouter into index.js. We’ve also imported the App component
from App.js. App.js, as you might have guessed, is the entry point to React
components.
The above code creates a history instance for our entire App component.
/* Import statements */
/* Home component */
<h2>Home</h2>
</div>
/* Category component */
<div>
<h2>Category</h2>
</div>
/* Products component */
<div>
<h2>Products</h2>
</div>
/* App component */
return (
<div>
<li><Link to="/">Homes</Link></li>
<li><Link to="/category">Category</Link></li>
<li><Link to="/products">Products</Link></li>
</ul>
</nav>
</div>
Inside the App component, we’ve written the logic for routing.
The <Route>‘s path is matched with the current location and a component
gets rendered. The component that should be rendered is passed in as a
second prop.
Here / matches both / and /category. Therefore, both the routes are
matched and rendered. How do we avoid that? We should pass the exact=
{true} props to the router with path='/':
If you want a route to be only rendered when the paths are exactly the
same, you should use the exact props.
Assessment: Quiz
We use exact={true} to impose further restrictions on path matching.
True False
The Route component exists in React modules.
True False
In which path will the login component appear?
/login /login/person /
<Route> has three props that you can use to define what gets rendered:
If the router’s path and the location are successfully matched, an object is
created and we call it the match object. The match object carries more
information about the URL and the path. This information is accessible
through its properties as listed below:
match.url. A string that returns the matched portion of the URL. This is
particularly useful for building nested <Link>s
match.path. A string that returns the route’s path string — that
is, <Route path="">. We’ll be using this to build nested <Route>s.
match.isExact. A boolean that returns true if the match is exact (without
any trailing characters).
match.params. An object containing key/value pairs from the URL parsed
by the Path-to-RegExp package.
Switch Component
Before we proceed to the demo code, let's get acquainted with
the <Switch> component.
When multiple <Route>s are used together, all the routes that match are
rendered inclusively. Consider this code from demo 1. We’ve added a new
route to demonstrate why <Switch> is useful.
<Route exact path="/" component={Home}/>
<Route path="/:id" render = {()=> (<p> I want this text to show up for
all routes other than '/', '/products' and '/category' </p>)}/>
If the URL is /products, all the routes that match the location /products are
rendered. So, the <Route> with path :id gets rendered along with
the Products component. This is by design. However, if this is not the
behavior you’re expecting, you should add the <Switch> component to your
routes. With <Switch>, only the first child <Route> that matches the location
gets rendered.
</switch>
src/App.js
import React from 'react';
return (
<div>
<li>
<Link to="/">Homes</Link>
</li>
<li>
<Link to="/category">Category</Link>
</li>
<li>
<Link to="/products">Products</Link>
</li>
</ul>
</nav>
<Switch>
</Switch>
</div>
);
};
src/Category.jsx
import React from 'react';
<li><Link to={`${match.url}/shoes`}>Shoes</Link></li>
<li><Link to={`${match.url}/boots`}>Boots</Link></li>
<li><Link to={`${match.url}/footwear`}>Footwear</Link></li>
</ul>
</div>)
name: 'running-shoes'
src/Products.jsx
const productData = [
{
id: 1,
status: 'Available'
},
id: 2,
},
id: 3,
status: 'Available'
},
id: 4,
},
];
src/Products.jsx
/* Import statements have been left out for code brevity */
const productsData = [
id: 1,
status: 'Available'
},
//The rest of the data has been left out for code brevity.
];
return(
<li>
<Link to={`${match.url}/${product.id}`}>
{product.name}
</Link>
</li>
})
return(
<div>
<div>
<div>
<h3> Products</h3>
</div>
</div>
<Route path={`${match.url}/:productId`}
render={() => (
)}
/>
</div>
var productData;
if(product)
productData = <div>
<p>{product.description}</p>
<hr/>
<h4>{product.status}</h4> </div>;
else
return (
<div>
<div>
{productData}
</div>
</div>
)
}
The find method is used to search the array for an object with an id
property that equals match.params.productId. If the product exists,
the productData is displayed. If not, a “Product doesn’t exist” message is
rendered.
React Routes
Protecting Routes
For the final demo, we’ll be discussing a few techniques on how to protect
routes. So, if someone tries to access /admin, they’d be required to log in
first. However, there are some things we need to cover before we can
protect routes.
Redirect
Like the server-side redirects, <Redirect> will replace the current location in
the history stack with a new location. The new location is specified by the
'to' prop. Here’s how we’ll be using <Redirect>:
<Redirect to={{pathname: '/login', state: {from: props.location}}} />
So, if someone tries to access the /admin while logged out, they’ll be
redirected to the /login route. The information about the current location
is passed via state, so in case the authentication is successful, the user
can be redirected back to the original location. Inside the child component,
you can access this information at this.props.location.state.
Custom Routes
A custom route is a fancy term for a route nested inside a component. If
we need to make a decision whether a route should be rendered or not,
writing a custom route is the way to go.
Here’s the custom route declared among other routes.
src/App.js
/* Add the PrivateRoute component to the existing Routes */
<Switch>
<Route exact path="/" component={Home} data={data}/>
</Switch>
Custom Routes
Here’s the definition for PrivateRoute:
src/App.js
/* PrivateRoute component definition */
return (
<Route
{...rest}
The route renders the Admin component if the user is logged in. Otherwise, the
user is redirected to /login. The good thing about this approach is that it is
evidently more declarative. PrivateRoute remains highly reusable.
Custom Routes
Finally, you can see the code for the Login component as shown below:
src/Login.jsx
const Login = props => {
const [redirectToReferrer, setRedirectToReferrer] = useState(false);
};
if (redirectToReferrer) {
return (
<div>
</div>
);
};
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true;
setTimeout(cb, 100);
};
The line below demonstrates object destructuring, which is a part of the ES6
specification.
const { from } = this.props.location.state || { from: { pathname:
'/' } }
Protecting Routes
Let us connect the dots together. Here’s the final demo of the application
that we've built using React router:
Demo
Assessment: Quiz
The custom routes are predefined in React.
True False
The redirect component replaces the current location in the history stack.
True False
Private routes are used to make components visible only to specific users.
True False
Conclusion
Recap
React Router is a powerful library that complements React by building
better and more declarative routes. Unlike the previous versions of React
Router, in version 4, everything is “just components”. Moreover, the new
design pattern perfectly fits into the React way of doing things.
We've covered:
Redux
Redux Overview
Introduction
One of the features provided by React is one-way data flow. Although this
feature can help developers debug and track data, when we get to state
management (especially when the application grows over time), it can
open the door to hell.
Redux is one of the most known and used state management libraries.
Managing states with Redux will be our main interest in this Super Skill.
Here is what we’re going to see:
What is Redux?
The mechanism that Redux uses to manage states.
Redux middleware.
Redux with hooks.
Assessment: Quiz
The state management is there to maintain and store the user's information until the
session ends.
True False
Redux is the only state manager for React
True False
Prop drilling refers to the process of passing the props through the component tree to
deliver data to certain components.
True False
What is Redux
What is Redux?
By definition, Redux is a predictable state container for JavaScript apps.
In other words, Redux is a stand-alone library. It helps you write
applications that behave consistently, run in different environments
(client, server, and native), and are easy to test.
On top of that, it provides a great developer experience, such as live code
editing combined with a time-traveling debugger.
Principles of Redux
The predictability of Redux is determined by the three most important
principles as given below:
Assessment: Quiz
Redux is:
A library that is used to manage state. Can only be used with React. None
of the above .
By using Redux, we can deliver the data to any component without affecting the
other.
True False
By putting the data in a store, only the component with privileges can access it.
True False
type: LOGIN_USER,
payload: {
username: 'sebastian',
password: '123456'
Action objects are created by using functions. These functions are called
action creators
function authUser(data) {
return {
type: LOGIN_USER,
payload: data,
};
Here you can see that the only purpose of an action creator
function is to return the action object as described.
Calling actions in the application is easy by using the dispatch
method:
dispatch(authUser(data));
What is a Reducer?
Reducers are the most important building block and it’s important to
understand the concept. Reducers are pure JavaScript functions that take
the current application state and an action object and return a new
application state:
const reducer = (state, action) => {
switch (action.type) {
case type1:
case type2:
default:
return state;
The important thing to notice here is that the state is not changed directly.
Instead a new state object (based on the old state) is created and the
update is done to the new state.
True False
Reducers specify how the state changes:
True False
Choose the correct statements
The action creator dispatches actions to the store. The reducer receives a
previous state and an action and returns a new state. The view is the one
responsible for triggering the reducer.
Redux vs react-redux
Redux gives you a store, and lets you keep states in it and extract them
out. It responds when the state changes. but that’s all it does.
It’s actually react-redux that lets you connect pieces of the state to React
components.
These libraries are like two peas in a pod, though. 99.999% of the time,
when anyone mentions “Redux” in the context of React, they are referring
to both of these libraries in tandem. So that's what you should keep in
mind when you see Redux mentioned on StackOverflow, Reddit or any
place else.
The redux library can be used outside of a React app too. It’ll work with
Vue, Angular, and even backend Node/Express apps.
Installing React-Redux
To start using Redux along with React, only you need to do is following
these steps:
2. Install redux
$ npm i redux
3. install react-redux
$ npm i react-redux
Redux folder architecture
Redux can make your life as a developer much easier or much harder
depending on the architecture that you follow.
Searching the web you can find a lot of architecture or different methods
to implement redux into your react application. The following is the one
that we recommend using it.
Assessment: Quiz
To use Redux, we need:
The Store
Create the store
The store is the one responsible for orchestrating the cogs. The store in
Redux is kind of magic and holds all the application's state.
Let's create a store to start playing with Redux. Under the store folder,
create a new file index.js,path to the file src/js/store/index.js, and
initialize the store.
// src/js/store/index.js
As you can see, store is the result of calling createStore, a function from
the Redux library. createStore takes a reducer as the first argument and in
our case we passed in rootReducer (not yet present).
The most important concept to understand here is that the state in Redux
comes from reducers.
createStore function
createStore(reducer, [preloadedState], [enhancer])
Creates a Redux store that holds the complete state tree of your app.
There should only be a single store in your app.
Arguments:
the arguments putted between [ ] mean that this arguments are optional.
The createStore function returns a store ( an object that holds the the
complete state of your application.
The Reducer
Create a reducer
What’s a reducer?
A Redux reducer is just a JavaScript function. It takes two
parameters: the current state and action.
In other words, the reducer must be pure. A pure function returns the
same output for the given input. Despite this terminology reasoning about
a reducer is not that hard.
Create a reducer
In our example we'll be creating a simple reducer which takes initial state
and action as parameters.
Create a new file under the folder Reducers named rootReducer.js.
counter: 0
};
return state;
};
Assessment: Quiz
Reducer is a pure JavaScript function.
True False
The third principle of Redux prescribes that the state is immutable and cannot
change in place.
True False
A reducer only need an intialState parameter.
True False
The Actions
The need of actions
Redux reducers are without doubt the most important concept in Redux.
Reducers produce the state of an application.
But how does a reducer know when to generate the next state?
The second principle of Redux says the only way to change the state is by
sending a signal to the store. This signal is an action. So "dispatching an
action" means sending out a signal to the store.
The reassuring thing is that Redux actions are nothing more than
JavaScript objects. This is how an action looks like:
type: "INCREMENT_COUNTER",
payload: {
value: 1
The type property drives how the state should change and it's always
required by Redux. The payload property instead describes what should
change, and might be omitted if you don't have new data to save in the
store.
Create actions:
As a best practice in Redux we wrap every action within a function, so that
object creation is abstracted away. Such function takes the name of action
creator: let’s put everything together by creating a simple action creator.
type: "INCREMENT_COUNTER",
payload
});
Create actions
You can notice that the type property is a string. Strings are prone to
typos and duplicates and for this reason it's better to declare actions as
constants. Here come the role of the directory constants. Under this folder
create a new file actions-types.js
// src/js/constants/action-types.js
type: INCREMENT_COUNTER,
payload
const initialState = {
counter: 0
};
switch (action.type) {
case INCREMENT_COUNTER:
return {
counter : state.counter + 1
return state;
};
Example
Example
During this skill, we are going to explore an example starting from scratch.
To see the big picture.
First, let’s start by creating our react application
$ npx create-react-app blog
Now let’s set the component tree, we are going to create a folder
component that contains the component we are using
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>)}
</div>
//CreatePost.js
e.preventDefault()
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="Title">Title</label>
</div>
<div>
<label htmlFor="Content">Content:</label>
</div>
<div>
</div>
</form>
//App.js
return (
<div className="App">
<CreatePost/>
<PostList/>
</div>
);
Setup Redux
To start working with Redux, first, we start by installing react and react-
redux library
$ npm i redux react-redux
Then we are going to follow the architecture that we talked about in the
previous slides.
//src/JS/store.js
//src/JS/Reducers/rootReducers.js
const initialState = {
posts: [
{
id: 1,
switch (action.type) {
case ADD_ARTICLE:
return {
default:
return state
// src/JS/Constants/actions-types.js
// src/JS/Actions/actions.js
return {
type: ADD_ARTICLE,
payload: newPost
}
}
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
As you can see from the code above, the component Provider needs a props
named store, through this props we pass the redux store to the wrapped
hierarchy ( which in our case the whole App )
return {
posts: state.posts
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>)}
</div>
Handle Actions
The next step in our project is to make the component CreatePost work
and add the new posts to the store. To do so, we are going to use the
mapDispatchToProps function, like shown in the example below
import React, { useState } from 'react'
return {
e.preventDefault()
props.addArticle({
id: Date.now(),
title,
content
})
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="Title">Title</label>
</div>
<div>
<label htmlFor="Content">Content:</label>
</div>
<div>
</div>
</form>
Go ahead and try this example for your own. You can find the whole
project at this link
Assessment: Quiz
The Provider component is imported from
True False
Redux Toolkit
What is Redux-toolkit?
React and Redux believed to be the best combo for managing state in
large-scale React applications. However, the configuration and the
enormously required boilerplate made it a little bit hard to understand and
manipulate.
Here came the role of the redux toolkit.
Redux-toolkit is a new way to implement Redux, a more functional way.
It's cleaner, you write fewer lines of code and we get the same Redux
state management, we have come to love and trust. The best part is it
comes with redux-thunk already built into it. Plus they use immerJs to handle
all the immutability, so all we need to think about is what needs to get
done.
Main features of Redux Tool Kit
The following function is used by Redux Took Kit, which is an abstract of
the existing Redux function. These function does not change the flow of
Redux but only streamline them in a more readable and manageable
manner.
You can use the above function to simplify the boilerplate code in Redux,
especially using the createAction and createReducer methods. However,
this can be further simplified using createSlice, which automatically
generates action creator and reducer functions.
Actions
type: GET_USERS,
payload: data,
});
};
dispatch({
type: CREATE_USER,
payload: data,
});
};
dispatch({
type: DELETE_USER,
payload: data,
});
};
Reducers
const initialState = {
errorMessage: "",
loading: false,
users:[]
};
switch (type) {
case GET_USERS:
case CREATE_USER:
return { ...state, users: [payload,...state.users],
loading: false };
case DELETE_USER:
return { ...state,
, loading: false };
default:
return state;
};
Now let's see how we can simplify and achieve the same functionality by
using createSlice.
import { createSlice } from '@reduxjs/toolkit';
users: [],
loading: false,
error: false,
};
name: 'user',
initialState,
reducers: {
state.users = action.payload;
state.loading = true;
state.error = false;
},
state.users.unshift(action.payload);
state.loading = false;
},
state.loading = false;
},
},
});
As you can see now all the actions and reducers are in a simple place
wherein a traditional redux application you need to manage every action
and its corresponding action inside the reducer. when
using createSlice you don’t need to use a switch to identify the action.
When it comes to mutating state, a typical Redux flow will throw errors
and you will require special JavaScript tactics like spread
operator and Object assign to overcome them. Since the Redux toolkit
uses Immer, you do not have to worry about mutating the state. Since a
slice creates the actions and reducers you can export them and use them
in your component and in Store to configure the Redux without having
separate files and directories for actions and reducers as below.
import { configureStore } from "@reduxjs/toolkit";
reducer: {
user: userSlice,
},
});
What is Middleware?
Redux middleware intermediates Action Creators and Reducers. The
Middleware intercepts the action object before a Reducer receives it and
gives it the functionality to perform additional actions or enhancements
with respect to the action dispatched.
Advantages of Middleware
Why use it?
The action/reducer pattern is very clean for updating the state within an
application. But what if we need to communicate with an external API? Or
what if we want to log all of the actions that are dispatched? We need a
way to run side effects without disrupting our action/reducer flow.
We can run side effects (like API requests) in response to a specific action
or in response to every action that is dispatched (like logging). There can
be numerous Middlewares that an action passes through before ending in
a reducer.
Advantages of Middleware
The Redux middleware syntax is a mouthful: a middleware function is a
function that returns a function and that returns a function.
The first function takes the store as a parameter, the second takes
a next function as a parameter, and the third takes the action dispatched
as a parameter.
The store and action parameters are the current Redux store and the
action being dispatched. The real magic is found in the next() function.
The next() function is what you call to say "this middleware is done
executing, pass this action to the next middleware". In other words,
middleware can be asynchronous.
const reduxMiddleware = store => next => action => {
. . . . . .
next(action);
};
Logging action
Logging: one of the benefits of Redux is that it makes state changes predictable
and transparent. Every time an action is dispatched, the new state is computed
and saved. The state cannot change by itself, it can only change as a
consequence of a specific action.
Wouldn't it be nice if we logged every action that happens in the app, together
with the state computed after it? When something goes wrong, we can look back
at our log and figure out which action corrupted the state.
Logger is the middleware function that will log action and state.
const logger = store => next => action => {
console.log('dispatching', action)
return result
}
Now only modify the store.
const store = createStore(reducer, applyMiddleware(logger));
Assessment: Quiz
The middleware is placed between the action and the reducer.
True False
The applyMiddlewares() method is imported from react-redux.
True False
Asynchronous requests exist by default in Redux without the usage of middlewares.
True False
Redux thunk
What’s redux-thunk?
Thunk is another word for a function but it’s not just any old function. It’s a
special (and uncommon) name for a function that’s returned by another.
function wrapper_function() {
};
You already know this pattern. You just don’t call it “thunk.” If you want to
execute the “do stuff now” part, you have to call it like wrapper_function()
() – calling it twice, basically.
// 2. has a type
type: "USER_LOGGED_IN",
userName: "dave"
Redux thunk:
Since it’s kind of annoying to write those objects by hand all the time (not
to mention error-prone), Redux has the option of “action creators” to
stamp these things out:
function userLoggedIn() {
return {
type: "USER_LOGGED_IN",
username: "dave"
};
It’s the same exact action, but now you can “create” it by calling the
userLoggedIn function. This just adds one layer of abstraction.
Instead of writing the action object yourself, you call the function, which
returns the object. If you need to dispatch the same action in multiple
places around your app, writing action creators will make your job easier.
Redux thunk:
Actually Redux action does nothing. They are nothing but objects. To make
them complete a concrete action (Calling an API, trigger another function
…) we have to make sure that the code lives inside a function. This
function (also called the thunk) is a bundle of work to be done. Right now
our action creator is performing an action. Like it’s shown in the example
below
function getUser() {
return function() {
return fetch("/current_user");
};
Redux thunk:
If only there was some way to teach Redux how to deal with functions as
actions.
return axios.post("/logout").then(function() {
dispatch(userLoggedOut());
});
};
the getState function can be useful for deciding whether to fetch new data
or return a cached result, depending on the current state.
Redux thunk:
Set up redux-thunk in your project.
If you have a project that already has Redux set up, adding redux-thunk
will be a two-step process.
First, install the package.
npm install --save redux-thunk
Then, wherever you have your Redux setup code, you need to import
redux-thunk and insert its middleware into Redux:
// You've probably already imported createStore from 'redux'
Just make sure you wrap thunk in the applyMiddleware call or else it won’t work.
After this, you’re all set: you can now dispatch functions that do whatever you
need them to.
Assessment: Quiz
The basic definition of thunk is that it is a function that returns another function.
True False
We can do an API call from a reducer.
True False
To install redux thunk, we need to run:
npm install --save redux-thunk npm i redux-thunk npm install --save redux
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
useSelector()
mapStateToProps and connect argument:
We replace our famous mapStateToProps and connect argument with this
selector hook: useSelector() which allows us to extract data from the
Redux state store.
It will be called with the entire state of the Redux store as its only
argument.
useSelector() also subscribes to the Redux store and runs our selector
each time an action is sent.
This works as long as the selector does not maintain any state. However,
memoizing selectors (e.g. created via useSelector() from reselect) have an
internal state and that is why they must be used with care.
When the selector only depends on the state, ensure that it is declared
outside of the component so that the same selector instance is used for
each render.
useSelector(): exemple
Example : In the example below, we are going to use
the createSelector nad useSelector.
import React from "react";
);
export const DoneTodosCounter = () => {
return <div>{NumOfDoneTodos}</div>;
};
return (
<>
<DoneTodosCounter />
</>
);
};
useDispatch()
mapDispatchToProps: This function is replaced by
a “useDispatch” function. This function returns a reference to the
dispatch function from the Redux store. We may use it to dispatch actions
as needed.
import React from "react";
return (
<div>
<span>{value}</span>
</button>
</div>
);
};
useCallback()
Pass an inline callback and an array of dependencies. useCallback will
return a memoized version of the callback that only changes if one of the
dependencies has changed.
This is useful when passing callbacks to optimized child components that
rely on reference equality to prevent unnecessary renders.
const memoizedCallback = useCallback(
() => {
doSomething(a, b);
},
[a, b],
);
Custom context
The <Provider> component allows us to specify an alternate context via the
context prop. This is useful if we’re building a complex reusable
component and we don't want our store to collide with any Redux store
our consumers' applications might use.
To access an alternate context via the hooks API, use the hook creator
functions:
import React from "react";
import {
Provider,
createStoreHook,
createDispatchHook,
createSelectorHook
} from "react-redux";
// Export your custom hooks if you wish to use them in other files.
return (
{children}
</Provider>
);
Assessment: Quiz
By using Redux hooks, we can ditch the connect function.
True False
useSelector() hook replaces the
mapStateToProps mapDispatchToProps
The hook that replaces mapDispatchToProps is
After this Super Skill, we all agree that Redux is a very powerful tool when
it comes to state management.
However, understanding its architecture can be a little bit tricky but once
we understand it, it will make state management very easy and organized.
The main idea behind Redux is to centralize the data in one store. That
store will be managed via the reducers. These reducers are triggered via
an action which can be fired from a user interaction with the application.
The redux library also offers a sets of hooks that, can replace the old
structure using the class based architecture.
API
Understanding API
Introduction
Up until now, we have made incredible progess in frontend web
development and learned most of what there is to know. However, there is
one more thing that is necessary for our frontend application to
communicate with the backend server.
What is an API?
What are web services?
What is the request/response approach?
Understanding API
What Is an API?
The term “API” stands for Application Programming Interface. If you break
that down word by word, you can get a pretty good grasp of what it
means.
Example
To describe the concept in further detail, we need to comprehend the
basics. Let’s start with the analogy of a restaurant menu. When we go to a
restaurant to eat, we choose from what is provided in the menu. At this
point, we convey our choices to the waiter. He/she then takes our order to
the chef who prepares our meal and our food arrives so we can enjoy a
nice meal. At this stage, it's only natural to ask ourselves: do we know
what the chef used to cook our fish or steak? How was it prepared? This
back-and-forth analogy serves as a starting point for our explanation.
Why? Because with an API, we really don’t know what’s going on behind
the scenes at the restaurant. All we really know is that we gave our order,
it was processed and out comes our dinner on a nice plate.
Let’s get back to the web development world. The API provides us with
data that we do not necessarily know how it has been created or served.
Assessment: Quiz
What does API stand for?
Application Programming Interface Application Progressive Interface
Asynchronous Post Interface
Google Maps' API is a private API.
True False
API only works with web applications.
True False
Web service
Introduction
A web service is a resource that is made available on the internet.
Therefore, web services, by definition, require a network.
The term “web service” is defined by W3C (the World Wide Web
Consortium), so it technically follows a whole host of standards.
To test web services, developers often use Postman.
Assessment: Quiz
A web service is
True False
All Web services are APIs but not all APIs are Web services.
True False
Requests : Methods
Requests
We can imagine the web browser as the client and the computer
application that hosts a web site as the server.
Methods
The most-commonly-used HTTP verbs (or methods, as they are properly
called) are POST, GET, PUT, PATCH, and DELETE. These correspond to
create, read, update, and delete (or CRUD) operations. There are a
number of other verbs too, but they are used less frequently. One of those
methods are OPTIONS and HEAD. These are used more often than others.
POST
The POST method is used to send data from the client (browser)
to the server. As we can see in the example below, we used
Postman to enter the URL 127.0.01 on the port 3000 with a
POST method. The body of this request contains the email and
the password.
GET
In this example, we use the GET method to fetch data from the API.
PUT
PUT is used to update requests and to modify entries in the database. So,
generally PUT requests are sent with an ID as a query or a params and the
new data is shown in the body.
//id as query
http://localhost:3000/user/profile/?id=5e3bebed40dfda2656da1788
//id as params
http://localhost:3000/user/profile/5e3bebed40dfda2656da1788
PATCH
Delete
In this example, we sent a request to delete the user and the method
DELETE is used with the ID 5e3bebed40dfda2656da1788
Conclusion
HTTP defines a set of request methods that indicate the wanted action to
be performed on a given resource. Even though they can be nouns, these
request methods are sometimes referred to as HTTP verbs, you could
check https://www.w3schools.com/tags/ref_httpmethods.asp.
Assessment: Quiz
We use PUT and PATCH to
Client Server
The DELETE method needs a query or a parameter (like ID, or name ….) for it to
function.
True False
Response
Response: Introduction
HTTP Response is the packet of information that is sent by the server to the
client in response to an earlier Request (GET, POST, PUT ….) that was made by a
client. An HTTP Response contains the information requested by the client.
Status
HTTP response status codes indicate whether a specific HTTP request has
been successfully completed or not. Responses are grouped in five
classes:
Status: example
HTTP response status description:
The Status-Code element in a server response is a 3-digit integer where
the first digit of the Status-Code defines the class of response and the last
two digits do not have any categorization role. There are 5 values for the
first digit. Here is a table describing the existing status value.
In the table below, we find the most used response status.
Body
Body
Response Body contains the resource data that was requested by the
client.
In the example below, City Hyderabad was requested for the weather
data. If we take a look at the response body, it contains the city's weather
information. It also has information about Temperature, Humidity, Weather
description and more of the city's weather properties.
Response Body:
"City": "Hyderabad",
"WeatherDescription": "haze",
To summarize, an API needs to specify the responses for all API operations.
Each operation must have at least one response defined and it's usually a
successful response. A response is defined by its HTTP status code and the
data returned in the response's body and/or headers.
Assessment: Quiz
The HTTP message consists of a header and a body that are separated by a line.
True False
A GET request is sent to the server to retrieve a product. The request completed
successfully but the requested product does not exist in the database. The response
status code should be:
Response Body contains the resource data that was requested by the client.
Response Body is all the packets of information that are sent by a server to a client.
Specifically, we'll make use of the Fetch API and axios as examples for how
to request and use data.
Example APIs
ProgrammableWeb is a site that tracks more than 15,500 APIs. Google
Maps, Twitter, YouTube, Flickr and Amazon Product Advertising as some of
the most popular APIs. The following list contains several examples of
popular APIs:
1. Google Maps API: Google Maps APIs lets developers embed Google
Maps on webpages using a JavaScript or Flash interface. The Google
Maps API is designed to work on mobile devices and desktop
browsers. Link to API: Link
3. Flickr API: The Flickr API is used by developers to access the Flick
photo sharing community data. The Flickr API consists of a set of
callable methods, and some API endpoints. Link to API: Link
This is the base URL. Everything that follows it is known as a URL path.
To find the base URL of your website, go to the site's front page. What you
see in the address bar on your site's front page is the base URL of your
website.
Path: /v1/lead/
Resource: 318582.json
Assessment: Quiz
The Twitter API helps developers to hack into twitter accounts.
True False
What is an URL base?
It’s the consistent part of a url It’s a type of an email address it‘s a module
used by React.
The query parameter is the parameter that is used after
"?" query= !!
What’s fetch?
To fetch data from an API, we can use the JavaScript fetch method. We can
also use an external library like axios, request, superagent, supertest and
many others.
In this Super Skill, we are going to use the fetch method.
The fetch method is provided by web APIs and it’s supported by almost all
the new browser versions.
In this part, we are going to get the list of courses from algolia API on
Redux.
"https://hn.algolia.com/api/v1/search?query=redux"
useEffect(() => {
function fetchData() {// the function to fetch data from the api
fetch("https://hn.algolia.com/api/v1/search?query=redux")
fetchData();
}, []);
};
function fetchData() {
fetch("https://hn.algolia.com/api/v1/search?query=redux")
fetchData();
}, []);
return (
<div>
<ul>
{data.map(course => (
<li>
</li>
))}
</ul>
</div>
);
};
What’s JSON?
JSON (JavaScript Object Notation) is the most widely used data format for
data interchange on the web. This data interchange can happen between
two computer applications at different geographical locations or running
within the same machine.
Assessment: Quiz
The fetch method can be used after installing the fetch API module.
True False
What is true about JSON?
JSON is a data format for data interchange on the web JSON is a human and
machine readable format JSON is a programming language JSON is a React
library JSON is built in a structure of collection of name/value pairs.
The JSON document can contain methods.
True False
fetch("https://jsonplaceholder.typicode.com/users", {
headers: {
Accept: "application/json",
"Content-Type": "application/json"
})
e.preventDefault();
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
};
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Person Name:
</label>
<button type="submit">Add</button>
</form>
</div>
);
};
Assessment: Quiz
The first argument in the POST method is:
True False
The data sent in the request body should only be an object.
True False
Install Axios
To install axios we simply run the following command:
npm i axios
// or
Use Axios
Axios syntax is mostly like the fetch API.
To Perform a get request:
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
axios
.post("/user", {
firstName: "Fred",
lastName: "Flintstone"
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
Chaining request
Axios comes with build in feature which gives us the ability to send
multiple requests.
const requestOne =
axios.get("https://api.storyblok.com/v1/cdn/stories/health?
version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt");
const requestTwo =
axios.get(https://api.storyblok.com/v1/cdn/datasources/?
token=wANpEQEsMYGOwLxwXQ76Ggtt");
const requestThree =
axios.get("https://api.storyblok.com/v1/cdn/stories/vue?
version=published&token=wANpEQEsMYGOwLxwXQ76Ggtt");
axios
console.log(firstResponse.data,secondResponse.data,
thirdResponse.data);
})
.catch(errors => {
console.error(errors);
});
Assessment: Quiz
Axios is promise base handler
True False
Axios is built in module with Node.js
True False
The third parameter in the post method is mandatory
True False
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/7.22.0',
accept: '*/*',
'cache-control': 'no-cache',
'postman-token': '35f27261-d4da-47d7-b540-9216d4fa694e',
host: '127.0.0.1:3001',
connection: 'keep-alive'
Headers:
The REST headers and parameters contain a wealth of information that
can help you track down issues when you encounter them. HTTP Headers
are an important part of the API request and response as they represent
the meta-data associated with the API request and response. Headers
carry information for:
Other than the above categories HTTP headers also carry a lot of other
information around HTTP connection types, proxies etc. Most of these
headers are for management of connections between client, server and
proxies and do not require explicit validation through testing.
Headers:
Headers are mostly classified as request headers and response headers,
know the major request and response headers. You will have to set the
request headers when you are sending the request for testing an API and
you will have to set the assertion against the response headers to ensure
that right headers are being returned.
The headers that you will encounter the most during API testing are the
following, you may need to set values for these or set assertions against
these headers to ensure that they convey the right information and
everything works fine in the API:
Accept-Charset: This is a header which is set with the request and tells
the server about which character sets are acceptable by the client.
Content-Type: Indicates the media type (text/html or text/JSON) of the
response sent to the client by the server, this will help the client in
processing the response body correctly.
Cache-Control: This is the cache policy defined by the server for this
response, a cached response can be stored by the client and re-used till
the time defined by the Cache-Control header.
Headers:
The HTTP Header contains information about the HTTP Body and the
Request/Response.
Information about the body is related to the content of the Body such as the
length of the content inside the body.
The information about Request/Response is the general information about the
request/response and it is not specific to the content of the body, example at
what time the Request was made
The properties in header are specified as name-value pair which are separated
from each other by a colon ‘:’, (example name:value)
Headers:
Request Header: is present when you make a request to the server, it
contains information about the request such as the URL that you have
requested, the method(GET, POST, HEAD) ,the browser used to generate
the request and other info.
Example
User-Agent:”Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101
Firefox/41.0″
Response Header: is sent from the server after the user sends a request
for a particular page or resource and it contains information such as the
encoding used in the content, the server software that is used on the
server machine to generate the response and other information.
Most of the sites usually hide their server information in order to make it
hard for hackers to know which software is being used on the server.
Assessment: Quiz
The http header of a request contain information about the server
True False
The authorization exists in the request body
True False
Http header contain information about the body
True False
Conclusion
API Recap
In the image above, you can see the relationship between the front-end
and the backend and how they communicate with each other.
During all the previous super skills, we have learned how to build a front-
end application. The API is the intermediate between the front-end and the
backend server
Let’s practice more with the checkpoint.
Right now, we are ready to work with external API, to make our application
consume external resources, and to interact with these resources. Let’s
practice more with the checkpoint.