Mark Mara

Mark Mara

1576120519

Redux Shopping Cart Refactor to The Context API and React Hooks

In the following documentation, we are going to, from the ground up, refactor a Redux shopping cart product’s data into the Context Provider pattern.

This guide’s primary focus will be on comparing and contrasting Redux vs. the Context API.

The refactor aims to provide a guided example, as well as deepen our understanding of state management in React, implementing various efficient scalable patterns.

Process Overview

The shopping cart application will be pulled from the official Redux GitHub repository to maintain a standard example environment.

We will trace the Flux-like pattern of Redux in the shopping cart app, and by focusing on the product data, implement a successful state management refactor by leveraging React Hooks and the Context API.

Guide Outline

  • Clone Redux.
  • Scalable state management analysis.
  • Tracing shopping cart product data.
  • Reducers and Actions.
  • Thunk and logger: middleware vs. dispatch.
  • Implement Context Provider pattern.
  • HOCs, HOFs, and Redux Connect().
  • Leveraging React Hooks and useContext.
  • setTimeout() vs. promises.
  • Final Context Provider pattern refactor.

Alright. So, let’s grab some coffee and get this show on the road.

React

Please note that a basic level requirement of Node and React is beneficial for getting started and for general concept comprehension.

Clone Redux

First off, go to the Redux GitHub repository.

Redux

Clone the source project by copying the SSH link and running git clonein the command prompt.

git clone git@github.com:reduxjs/redux.git

Copy the Shopping Cart folder which can be found in the folder directory: examples/shopping-cart and paste it somewhere where you can conveniently access it throughout this guide.

Now, using the terminal (Mac) command prompt, go cd shopping-cart into the shopping-cart folder directory and install all required node modules simply by running npm install.

Open the code source into your text editor and then launch the local development server by running npm start. We should now see the shopping cart application up and running in the browser.

Open up the DevTools Console (Chrome) to verify this and also note Redux Logger is activated and working.

Shopping Cart

Excellent. Now, let’s take a quick yet savory sip of coffee before proceeding.

Application Structure and API Emulation

Simply by viewing the shopping cart’s display in the browser, we can ascertain two main sections: the products section and the cart section.

  • The products section contains a list of products available to purchase including the title, price, and quantity. As well, there is an add to cart button to individually select products for the cart.
  • When we click on the iPad 4 Mini add to cart button, we see that the cart sectiongets updated, including the total price. If we scroll down to the Logger in the DevTools and check on the previous state vs. the next state, the products inventory is updated and reflected accordingly.

Next State Logger
Next State Logger

But where are we receiving our product’s item data to begin with?

Good question. In the Redux shopping cart project’s API folder, we see a products.json file with a list of items and a shop.jsfile, grabbing and exporting the array from products.json.

The shop.js getProducts object’s property has an additional setTimeout function set to 100 milliseconds to simulate an Async-esque operation of fetching the shopping cart items from a real-world API scenario.

const TIMEOUT = 100
export default { getProducts: (cb, timeout) => setTimeout(() => cb(_products), timeout || TIMEOUT),
buyProducts: (payload, cb, timeout) => setTimeout(() => cb(), timeout || TIMEOUT)}

If we change the TIMEOUT const numerical value to 2000 (two seconds) and go back to the browser and refresh, we’ll notice the initial products render will now take two full seconds before displaying: const TIMEOUT = 2000.

Having now located and assessed our API data structure and retrieval setup, let’s fully trace the state retrieval management process of the products data in Redux.

Products: Actions, Reducers, and Thunk Middleware

If we go into the actions folder, the index.jscontains the following code:

import shop from '../api/shop'
import * as types from '../constants/ActionTypes'
const receiveProducts = products => ({
type: types.RECEIVE_PRODUCTS,
products})
export const getAllProducts = () => dispatch => {
shop.getProducts(products => {
dispatch(receiveProducts(products))
})}

The receiveProducts establishes the type types.RECEIVE_PRODUCTS and a payload of products.

This type is set up as const in the ActionTypes file. It’s then passed to a switch statement in two reducers, visibleIds and byIds, located in the reducer folder in products.js.

Maintaining focus on the actions, also notice a getAllProducts function which returns a dispatch function that grabs the products.json from the shop and sends the data payload of products into our receiveProducts action.

Back in the main index.jsfile located in our src folder, if we remove our Thunk middleware: const middleware = [ ];, we receive the following error:

error

Since the action performs an emulated real-life API fetch, set to a setTimeout(), we need to implement Thunk to correctly process and handle the async action.

Have a contemplative sip or two of coffee and return Thunk back to the middleware: const middleware = [thunk].

We’ve now managed to complete a full assessment of the product’s data API display: How and where we’re receiving the data and managing it in our application.

With this assessment, let’s proceed by setting up the architecture for the Context Provider pattern.

Context Provider Pattern Setup

Back in the project’s src folder, create a new folder called providers and file inside of the folder named products.provider.js.

In the products provider file, we’re going to set up a products provider pre-test demonstration with the following code:

products.provider.js

import React,{createContext, useState} from 'react'

export const ProductsContext = createContext({
    test: ''
})

const ProductsProvider = ({children}) => {
    const [test] = useState('the products provider has been successfully connected :)')
    return (
        <ProductsContext.Provider value={{test}}>
            {children}
        </ProductsContext.Provider>
    )
}

export default ProductsProvider

The code above first brings in createContext to access the React Context API and the useState Hook. Then, we set our context to the constProductsContext where we initialize an object that takes the property of test which we set to an empty string.

After that, we create the ProductsProviderfunction which takes the object of children props as its parameter, passing the props of children through the Context.Provider.

Within, we initialize the state of test to a string: const [test] = useState(‘the products provider has been successfully connected :)’).

ProductsProvider then explicitly returns the ProductsContext to the Provider with a value of the object test passing in the state with the property of children.

Alright, let’s stop for a second. Might sound like a bit of mouthful, but it’s actually quite simple, except that it takes a bit of following in terms of how things are hooked up.

If you’re having trouble following, go back and take each step one at a time, slowly. Just make sure you follow the traces and it will make much more sense, otherwise, if you’ve managed to follow along up to this part, kudos and let’s keep moving!

The products Context is made aware of an empty string of test in which we initialize state by setting up a const test in the product’s Provider, also taking a string.

We can then set the state of test to the object property of test by setting the ProductsContext.Provider value={{test}} to an object receiving test.

Finally, pass the children over as a wrapper.

To enable the Provider to be wrapped around the component/container of our choosing, let’s simply go into the index.js filein thesrc folder, import the Provider, and wrap it around our application granting it access to the children.

index.js

import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { createLogger } from 'redux-logger'
import thunk from 'redux-thunk'
import reducer from './reducers'
import { getAllProducts } from './actions'
import App from './containers/App'
import ProductsProvider from './provider/products.provider'

const middleware = [thunk];
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger());
}

const store = createStore(
  reducer,
  applyMiddleware(...middleware)
)

store.dispatch(getAllProducts())

render(
  <ProductsProvider>
  <Provider store={store}>
    <App />
  </Provider>
  </ProductsProvider>,
  document.getElementById('root')
)

Note that the ProductsProvider wraps over the Redux store Provider illustrating it at the utmost top of our application’s state management tree.

Context Provider Pattern Test

Time to drink some more coffee and test if our new Context Provider is effectively working.

Go into the containers folder in productsContainer.js.We can now bring in the useContext Hook and destructure our test from the ProductsContext into our products container to see if it works.

productsContainer.js

import React,{useContext} from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { addToCart } from '../actions'
import { getVisibleProducts } from '../reducers/products'
import ProductItem from '../components/ProductItem'
import ProductsList from '../components/ProductsList'
import {ProductsContext} from '../provider/products.provider'

const ProductsContainer = ({ products, addToCart }) => {
  const {test} = useContext(ProductsContext)
  console.log(test)
return (
  <ProductsList title="Products">
    {products.map(product =>
      <ProductItem
        key={product.id}
        product={product}
        onAddToCartClicked={() => addToCart(product.id)} />
    )}
  </ProductsList>
)
    }
ProductsContainer.propTypes = {
  products: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.number.isRequired,
    title: PropTypes.string.isRequired,
    price: PropTypes.number.isRequired,
    inventory: PropTypes.number.isRequired
  })).isRequired,
  addToCart: PropTypes.func.isRequired
}

const mapStateToProps = state => ({
  products: getVisibleProducts(state.products)
})

export default connect(
  mapStateToProps,
  { addToCart }
)(ProductsContainer)

Our productsContainer.jsshould now be updated to the code above. Upon browser refresh, DevTools now displays the test log successfully.

DevTools

Very nice. Our Context Provider pattern for our product’s display is now fully connected and ready for implementation.

Let’s head back to our products.provider.js file and completely refactor the product’s data into our Context API setup.

Migrate Products Data to Context Provider

We’ll now update the products.provider.jscode. First, we’ll import the shop from our shop.js.

We’ll establish a new property in our context object for the products’ data and set it to an empty array. We’ll then import the useEffect Hook as well from React and create a products’ state also set to an empty array.

Then, we’ll leverage the useEffect Hook to render our product’s data by setting the hook to async to await grabbing the product’s data from our shop and setting the response to our products state.

We’ll leave an empty array in our useEffect so that the mounting life-cycle executes once, by default.

Finally, we’ll bring the product’s state into the Context Provider’s value object.

products.provider.js

import React,{createContext, useState, useEffect} from 'react'
import shop from '../api/shop'

export const ProductsContext = createContext({
    test: '',
    products: []
})

const ProductsProvider = ({children}) => {
    const [test] = useState('the products provider has been successfully connected :)')
    const [products, setProducts] = useState([])
    useEffect(async ()=> {
        const response = await shop.getProducts(products => products)
        setProducts(response)
},[])
    return (
        <ProductsContext.Provider value={{test, products}}>
            {children}
        </ProductsContext.Provider>
    )
}

export default ProductsProvider

Final Implementation and Async vs. Promises

Saving the newly updated code, let’s refill our coffee cups and head back to the productsContainer.js file.

Let’s update our products’ data to be called from our Products Provider instead of our Redux Provider by destructuring products off the ProductsContext and removing products destructured props from the ProductsContainer, as shown below.

productsContainer.js

After saving everything, we will now run into the following error.

error

No need to panic, this is expected behavior. Since setTimeout does not return a promise, async await will not execute accordingly to prevent JavaScript from running until the setTimeout interval value is completed.

To maintain the coded simulation effect of this API, let’s go back to the shop.jsfile and promisify the code.

Let’s create an async anonymous function and wrap a new Promise around the getProduct data retrieval property.

* Mocking client-server processing */
import _products from './products.json'
const TIMEOUT = 100
export default {
getProducts: async ()=> new Promise((cb, timeout) => setTimeout(() => cb(_products), timeout || TIMEOUT)),
buyProducts: (payload, cb, timeout) => setTimeout(() => cb(), timeout || TIMEOUT)
}

With the new promise patch modification, getProducts will now return a promise for our async useEffect to retrieve.

Saving this latest update, our product’s shopping cart data will once again successfully be displayed upon mounting.

Congratulations. We have now migrated our initial product’s data display from Redux into the newly instated Context Provider pattern.

Take a congratulatory sip or three of coffee and let’s do some final code clean-up and review.

Final Refactor and Conclusion

Back in our productsContainer.js file, we can delete our mapStateToProps const and remove it from our connect since our products’ data retrieval is no longer being managed by Redux.

export default connect(null,{ addToCart })(ProductsContainer)

Our application will continue to work as is it did before, demonstrating a successful refactor.

Just like Connect() is a higher-order component that wrapped around our productsContainer component to pass over the data state to props, our ProductsProvider now acts in its place.

The Products Context passes the children props of the products data state as the Products Provider wraps around the main application in our index.jsby being placed at the top of the app tree.

Although both implementations are effective, this guide in no way favors one over the other as an ultimate go-to.

It simply depends on each application and these are the decisions we need to think about carefully and make to achieve the most effective state management path for our applications.

This guide has purely been intended to simulate a refactor process and analysis of working with Context and Redux as a basic starting point.

Thank you for checking this out and I hope you found some of this helpful!

#reactjs #javascript #Redux

What is GEEK

Buddha Community

Redux Shopping Cart Refactor to The Context API and React Hooks
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

How to Use Redux with React Hooks🔥 ( REDUX HOOKS )

Hello Friends,
In this Video, We are going to know How to use redux with react hook.
we have used redux inside Class based component with Connect() higher order component
but inside the functional based component , We couldnt use Connect!
So How can we use redux in fucntional based component ?
We will figure out it here !

Git Repository:
https://github.com/jaewonhimnae/reduxHooks-with-reactHooks

#redux #redux hooks #react hooks #react

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

DARK MODE App with REACT Hook , REDUX Hook, Styled Components

Thank you for watching this video !
git repository :
https://github.com/jaewonhimnae/react-darkmode-app

#react hook #react #redux #redux hook