Handling Deeply Nested Object Updates in React State with useReducer
I'm relatively new to this, so bear with me. I'm working through a tutorial and I'm trying to manage a deeply nested state object in a React 18 application using `useReducer`. The structure of my state looks like this: ```javascript const initialState = { user: { name: '', preferences: { theme: 'light', notifications: true, }, }, }; ``` I want to update the `theme` value within `preferences` when a user switches themes, but I keep running into issues where the state doesn't update as expected, or I get an behavior about trying to access properties of `undefined`. Here's my reducer function: ```javascript const reducer = (state, action) => { switch (action.type) { case 'SET_THEME': return { ...state, user: { ...state.user, preferences: { ...state.user.preferences, theme: action.payload, }, }, }; default: return state; } }; ``` And when I dispatch the action, I do it like this: ```javascript const switchTheme = (newTheme) => { dispatch({ type: 'SET_THEME', payload: newTheme }); }; ``` However, when I call `switchTheme('dark')`, I receive this behavior in my console: `want to read properties of undefined (reading 'preferences')`. I suspect it might be an scenario with how I'm destructuring the state or the initial state, but I'm not sure. I've also verified that the initial state is correctly set when the component first mounts. Any pointers on how to correctly handle this nested state update without running into these errors would be greatly appreciated! Is there a better pattern or library to manage such deeply nested updates in React? This is for a REST API running on Linux. I'm working with Javascript in a Docker container on Ubuntu 20.04. Could someone point me to the right documentation?