CodexBloom - Programming Q&A Platform

how to access nested properties of state in React with useReducer, throws TypeError

πŸ‘€ Views: 74 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
react typescript usestate usereducer TypeScript

I'm deploying to production and I'm stuck on something that should probably be simple... I need some guidance on I'm migrating some code and Hey everyone, I'm running into an issue that's driving me crazy... I am using React with TypeScript and the `useReducer` hook to manage complex state. I have a nested state structure, and I'm working with a `TypeError: want to read properties of undefined` when trying to access nested properties in my state. Here’s the relevant part of my reducer: ```typescript interface State { user: { name: string; age: number; address: { city: string; zip: string; }; }; } const initialState: State = { user: { name: '', age: 0, address: { city: '', zip: '' } } }; const reducer = (state: State, action: any) => { switch (action.type) { case 'UPDATE_USER': return { ...state, user: { ...state.user, ...action.payload } }; default: return state; } }; const [state, dispatch] = useReducer(reducer, initialState); ``` In a component, I'm trying to dispatch an action to update the user's address, like this: ```typescript const updateAddress = () => { dispatch({ type: 'UPDATE_USER', payload: { address: { city: 'New York', zip: '10001' } } }); }; ``` However, when I try to access `state.user.address.city` after dispatching this action, it throws the TypeError. I've checked the shape of my `state` using `console.log(state)` before and after the dispatch, and it seems to be correct. I tried ensuring that my action payload matches the structure, but I still get the behavior. What could be causing this scenario? Am I missing something in how I’m updating the state? I’m using React 17 and TypeScript 4.3. I'm working on a web app that needs to handle this. Am I missing something obvious? Is there a simpler solution I'm overlooking? What are your experiences with this? Could someone point me to the right documentation?