concept payload in category react
appears as: payload, payload

This is an excerpt from Manning's book React Hooks in Action.
That seems like a bit of overkill for our two little actions, but having a reducer makes it easy to extend. Let’s add three more actions, for adding and subtracting arbitrary numbers to and from the counter and for setting the counter to a specified value. To be able to specify extra values with our action, we need to beef it up a bit - let’s make it an object with a type and a payload. Say we want to add three to the counter, our action looks like this:
Figure 4.4 Pass the reducer a state object and an action object. The reducer updates the state based on the action type and payload. The reducer returns the new, updated state.
![]()
Listing 5.10 The BookablesList component loading its own data
import React, {useReducer, useEffect, Fragment} from "react"; import {sessions, days} from "../../static.json"; import {FaArrowRight, FaSpinner} from "react-icons/fa"; import reducer from "./reducer"; import getData from "../../utils/api"; #A const initialState = { group: "Rooms", bookableIndex: 0, hasDetails: true, bookables: [], isLoading: true, #B error: false #B }; export default function BookablesList () { const [state, dispatch] = useReducer(reducer, initialState); const {group, bookableIndex, bookables} = state; const {hasDetails, isLoading, error} = state; #C const bookablesInGroup = bookables.filter(b => b.group === group); const bookable = bookablesInGroup[bookableIndex]; const groups = [...new Set(bookables.map(b => b.group))]; useEffect(() => { dispatch({type: "FETCH_BOOKABLES_REQUEST"}); #D getData("http://localhost:3001/bookables") #E .then(bookables => dispatch({ #F type: "FETCH_BOOKABLES_SUCCESS", #F payload: bookables #F })) .catch(error => dispatch({ #G type: "FETCH_BOOKABLES_ERROR", #G payload: error #G })); }, []); function changeGroup (event) {} function changeBookable (selectedIndex) {} function nextBookable () {} function toggleDetails () {} if (error) { #H return <p>{error.message}</p> #H } #H if (isLoading) { #I return <p> #I <FaSpinner className="icon-loading"/>{" "} #I Loading bookables... #I </p> #I } #I return ( /* unchanged UI for bookables and details */ ); }