immerjs / use-immer

Use immer to drive state with a React hooks

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useImmerReducer cant handle initialState being null?

Sebastian-Nielsen opened this issue · comments

export const profileReducer = (
	draft: Data | null, action: Action
) => {
	if (action.type === "init") {
	        draft.something = action.date.something; 	           // TypeError: 'draft' is possibly 'null'     
		return;
	}
}

// somewhere else:
const [data, dispatch] = useImmerReducer(profileReducer, null);

I have a complex Data object that is fetched and fed into my useImmerReducer. The initialstate is thus empty {} or null. This causes typescript to exclaim that you now shouldn't do draft.<property> now that draft might be {} or null -- which is understandable.

I think you probably have already thought about this case, so I dont think it's a bug.

How are you supposed to useImmerReducer with a null as the initialState?

instead of assigning to draft, it is also allowed to return a new value. So you can return action.date.something.