reactjsobjectreact-hooksuse-reducernested-object

how to update nested object with useReducer in React?


How do I update the courseName using this use reducer? error: "cannot create property on courseName on string "science". I am assuming Im not accessing it correctly? I have been using useState but i want to learn useReducer for more complex objects.

import React, { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "update":
      return { object: (state.object.courseName = "Science") };

    default:
      return state;
  }
}

export default function TestPage() {
  const object = {
    courseName: "Mathematics",
    courseModules: [
      {
        moduleName: "module1",
        isComplete: false,
        lessons: [
          {
            lessonName: "Lesson1",
            isComplete: false,
            progress: 0,
          },
        ],
      },
    ],
  };

  const [state, dispatch] = useReducer(reducer, { object });

  function updateName() {
    dispatch({ type: "update" });
  }

  return (
    <div>
      <h1>{object.courseName}</h1>
      <button onClick={updateName}>submit</button>
    </div>
  );
}

Solution

  • You can spread your object and just override the one value.

      switch (action.type) {
        case "update":
          return { ...state, object: { ...state.object, courseName: "Science"}};
        default:
          return state;
      }