Skip to content

Examples/real world update #3922

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/real-world/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": ["react-app"]
}
11,518 changes: 7,330 additions & 4,188 deletions examples/real-world/package-lock.json

Large diffs are not rendered by default.

22 changes: 9 additions & 13 deletions examples/real-world/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,19 @@
"version": "0.0.1",
"private": true,
"devDependencies": {
"react-scripts": "^3.4.1",
"redux-devtools": "^3.5.0",
"redux-devtools-dock-monitor": "^1.1.3",
"redux-devtools-log-monitor": "^1.4.0",
"react-scripts": "^4.0.0",
"redux-logger": "^3.0.6"
},
"dependencies": {
"humps": "^2.0.0",
"lodash": "^4.17.19",
"normalizr": "^3.6.0",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"@reduxjs/toolkit": "^1.4.0",
"humps": "^2.0.1",
"lodash": "^4.17.20",
"normalizr": "^3.6.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-redux": "^7.2.1",
"react-router-dom": "^5.2.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
"redux": "^4.0.5"
},
"scripts": {
"start": "react-scripts start",
Expand Down
6 changes: 3 additions & 3 deletions examples/real-world/public/index.html
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>React App</title>
</head>
<body>
Expand Down
74 changes: 74 additions & 0 deletions examples/real-world/src/actions/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { normalize, schema } from 'normalizr'
import { camelizeKeys } from 'humps'

// Extracts the next page URL from Github API response.
const getNextPageUrl = response => {
const link = response.headers.get('link')
if (!link) {
return null
}

const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1)
if (!nextLink) {
return null
}

return nextLink.trim().split(';')[0].slice(1, -1)
}

const API_ROOT = 'https://api.github.com/'

// Fetches an API response and normalizes the result JSON according to schema.
// This makes every API response have the same shape, regardless of how nested it was.
export const callApi = async (endpoint, schema) => {
const fullUrl =
endpoint.indexOf(API_ROOT) === -1 ? API_ROOT + endpoint : endpoint

const response = await fetch(fullUrl)
const json = await response.json()
if (!response.ok) {
return Promise.reject(json)
}
const camelizedJson = camelizeKeys(json)
const nextPageUrl = getNextPageUrl(response)
return Object.assign({}, normalize(camelizedJson, schema), { nextPageUrl })
}

// We use this Normalizr schemas to transform API responses from a nested form
// to a flat form where repos and users are placed in `entities`, and nested
// JSON objects are replaced with their IDs. This is very convenient for
// consumption by reducers, because we can easily build a normalized tree
// and keep it updated as we fetch more data.

// Read more about Normalizr: https://github.com/paularmstrong/normalizr

// GitHub's API may return results with uppercase letters while the query
// doesn't contain any. For example, "someuser" could result in "SomeUser"
// leading to a frozen UI as it wouldn't find "someuser" in the entities.
// That's why we're forcing lower cases down there.

const userSchema = new schema.Entity(
'users',
{},
{
idAttribute: user => user.login.toLowerCase()
}
)

const repoSchema = new schema.Entity(
'repos',
{
owner: userSchema
},
{
idAttribute: repo => repo.fullName.toLowerCase()
}
)

// Schemas for Github API responses.
export const Schemas = {
USER: userSchema,
USER_ARRAY: [userSchema],
REPO: repoSchema,
REPO_ARRAY: [repoSchema]
}
215 changes: 99 additions & 116 deletions examples/real-world/src/actions/index.js
Original file line number Diff line number Diff line change
@@ -1,120 +1,103 @@
import { CALL_API, Schemas } from '../middleware/api'

export const USER_REQUEST = 'USER_REQUEST'
export const USER_SUCCESS = 'USER_SUCCESS'
export const USER_FAILURE = 'USER_FAILURE'

// Fetches a single user from Github API.
// Relies on the custom API middleware defined in ../middleware/api.js.
const fetchUser = login => ({
[CALL_API]: {
types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
endpoint: `users/${login}`,
schema: Schemas.USER
}
})

// Fetches a single user from Github API unless it is cached.
// Relies on Redux Thunk middleware.
export const loadUser = (login, requiredFields = []) => (dispatch, getState) => {
const user = getState().entities.users[login]
if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
return null
}

return dispatch(fetchUser(login))
}

export const REPO_REQUEST = 'REPO_REQUEST'
export const REPO_SUCCESS = 'REPO_SUCCESS'
export const REPO_FAILURE = 'REPO_FAILURE'

// Fetches a single repository from Github API.
// Relies on the custom API middleware defined in ../middleware/api.js.
const fetchRepo = fullName => ({
[CALL_API]: {
types: [ REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE ],
endpoint: `repos/${fullName}`,
schema: Schemas.REPO
}
})

// Fetches a single repository from Github API unless it is cached.
// Relies on Redux Thunk middleware.
export const loadRepo = (fullName, requiredFields = []) => (dispatch, getState) => {
const repo = getState().entities.repos[fullName]
if (repo && requiredFields.every(key => repo.hasOwnProperty(key))) {
return null
}

return dispatch(fetchRepo(fullName))
}

export const STARRED_REQUEST = 'STARRED_REQUEST'
export const STARRED_SUCCESS = 'STARRED_SUCCESS'
export const STARRED_FAILURE = 'STARRED_FAILURE'

// Fetches a page of starred repos by a particular user.
// Relies on the custom API middleware defined in ../middleware/api.js.
const fetchStarred = (login, nextPageUrl) => ({
login,
[CALL_API]: {
types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ],
endpoint: nextPageUrl,
schema: Schemas.REPO_ARRAY
import { createAsyncThunk } from '@reduxjs/toolkit'
import { callApi, Schemas } from './api'

/**
* Fetches a single user from Github API.
*/
export const loadUser = createAsyncThunk(
'loadUser',
async ({ login }, { rejectWithValue }) => {
try {
const response = await callApi(`users/${login}`, Schemas.USER)
return response
} catch (error) {
return rejectWithValue(error)
}
},
{
condition: ({ login, requiredFields }, { getState }) => {
const user = getState().entities.users[login]
// If the user is already cached, nothing will be requested or dispatched
const shouldProceed = !(
user && requiredFields.every(key => user.hasOwnProperty(key))
)
return shouldProceed
}
}
})

// Fetches a page of starred repos by a particular user.
// Bails out if page is cached and user didn't specifically request next page.
// Relies on Redux Thunk middleware.
export const loadStarred = (login, nextPage) => (dispatch, getState) => {
const {
nextPageUrl = `users/${login}/starred`,
pageCount = 0
} = getState().pagination.starredByUser[login] || {}

if (pageCount > 0 && !nextPage) {
return null
)

/**
* Fetches a single Repo from Github API.
*/
export const loadRepo = createAsyncThunk(
'loadRepo',
async ({ fullName }, { rejectWithValue }) => {
try {
const response = await callApi(`repos/${fullName}`, Schemas.REPO)
return response
} catch (error) {
return rejectWithValue(error)
}
},
{
condition: ({ fullName, requiredFields }, { getState }) => {
const repo = getState().entities.repos[fullName]
// If the repo is cached, nothing will be requested or dispatched
const shouldProceed = !(
repo && requiredFields.every(key => repo.hasOwnProperty(key))
)
return shouldProceed
}
}

return dispatch(fetchStarred(login, nextPageUrl))
}

export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST'
export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS'
export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE'

// Fetches a page of stargazers for a particular repo.
// Relies on the custom API middleware defined in ../middleware/api.js.
const fetchStargazers = (fullName, nextPageUrl) => ({
fullName,
[CALL_API]: {
types: [ STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_FAILURE ],
endpoint: nextPageUrl,
schema: Schemas.USER_ARRAY
)

/**
* Fetches a page of starred repos by a particular user.
*/
export const loadStarred = createAsyncThunk(
'loadStarred',
async ({ login }, { rejectWithValue, getState }) => {
const { nextPageUrl = `users/${login}/starred` } =
getState().pagination.starredByUser[login] || {}
try {
const response = await callApi(nextPageUrl, Schemas.REPO_ARRAY)
return response
} catch (error) {
return rejectWithValue(error)
}
},
{
condition: ({ login, nextPage }, { getState }) => {
const { pageCount = 0 } = getState().pagination.starredByUser[login] || {}
// Bails out if page is cached and user didn't specifically request next page.
const shouldProceed = !(pageCount > 0 && !nextPage)
return shouldProceed
}
}
})

// Fetches a page of stargazers for a particular repo.
// Bails out if page is cached and user didn't specifically request next page.
// Relies on Redux Thunk middleware.
export const loadStargazers = (fullName, nextPage) => (dispatch, getState) => {
const {
nextPageUrl = `repos/${fullName}/stargazers`,
pageCount = 0
} = getState().pagination.stargazersByRepo[fullName] || {}

if (pageCount > 0 && !nextPage) {
return null
)

/**
* Fetches a page of stargazers for a particular repo.
*/
export const loadStargazers = createAsyncThunk(
'loadStargazers',
async ({ fullName }, { rejectWithValue, getState }) => {
const { nextPageUrl = `repos/${fullName}/stargazers` } =
getState().pagination.stargazersByRepo[fullName] || {}
try {
const response = await callApi(nextPageUrl, Schemas.USER_ARRAY)
return response
} catch (error) {
return rejectWithValue(error)
}
},
{
condition: ({ nextPage, fullName }, { getState }) => {
const { pageCount = 0 } =
getState().pagination.stargazersByRepo[fullName] || {}
// Bails out if page is cached and user didn't specifically request next page.
const shouldProceed = !(pageCount > 0 && !nextPage)
return shouldProceed
}
}

return dispatch(fetchStargazers(fullName, nextPageUrl))
}

export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE'

// Resets the currently visible error message.
export const resetErrorMessage = () => ({
type: RESET_ERROR_MESSAGE
})
)
Loading