Redux basics - mosinn/DOCS-n-Snippets-n-Steps GitHub Wiki

React setLocalState() for localState's TypeScript type is

const onXXXFieldChange = (
    val: string | number | boolean | LabelAndValue,
    setLocalState: React.Dispatch<React.SetStateAction<MyXXXType | undefined>>
  ) => {

Any functional component that returns JSX, the return type is

React.ReactElement

Suppose I have to allow REDUX to maintain app state, which basically holds "Todos":

I want to PREPEND_TODO, APPEND_TODO or INSERT todos. ie 3 things

const state = { 
    todos: [
    {
    id: 1,
    title: "Eat",
    completed: true
    },
    {
    id: 2,
    title: "Sleep",
    completed: false
    }
    ]
    };

I have 3 action types therefore

HINT: Redux Action is NOT a simple NAME, but an Object with TWO parts - name (or TYPE or state TARGET KEY Locator for Reducer Switch case to let reducer know which STATE key to TARGET) + payload (ForStateChunkMutation)

I have 3 functions to produce those 3 actions types theorefore..so substitue XXX 3 times for 3 functions >>> therefore file is actionXXXes.ts

    const reduxActionXXXX = (data) => ({
        type: XXX_TYPE,
        payload: data
    });

I have, alternatively, and preferably, 3 https://redux-toolkit.js.org/api/createAction method calls to make, which takes Action -TYPE and Data's-TYPE

Eg. const setAccountInfo = createAction(MyActionType.SET_ACC_INFO)<AccInfo | undefined>();


I have 3 reducers to mutate state therefore

// Can be a separate reducer file - must then be imported in "rootReducer.ts", as thats the only reducer reduc is configured to know about
const sub_reducer_for_prepend_append = (state, action) => {
 swicth(action.type){
  case PREPEND_TODO: 
   return { // returning a copy of orignal state 
    ...state, //spreading the original state
    todos: [action.payload, ...state.todos] // new todos array
   }
case APPEND_TODO: 
  return { // returning a copy of orignal state 
   ...state, //copying the original state
   todos: [...state.todos, action.payload] //new todos array 
  }
  default: return state; // If no action matched, just return original state as a catch all scenario to not end up stateless
 }
}
// Can be a separate reducer file - must then be imported in "rootReducer.ts", as thats the only reducer reduc is configured to know about
const sub_reducer_for_insert = (state, action) => {
 swicth(action.type){
  case DELETE_TODO: 
   return {  // returning a copy of orignal state
    ...state, //copying the original state
    todos: state.todos.filter(todo => todo.id !== action.payload) 
                               // returns a new filtered todos array
  }
 }
}


To trigger a redux state change:

dispatch(myActions.setAccountInfo({<<payload>>}))

⚠️ **GitHub.com Fallback** ⚠️