I’m trying to do a conditional state update in react where some keys are only updated if another value changes (used to reset some values for settings to null if certain modes are selected). This pattern used to work fine (like years ago), but now it seems like React’s setState expects a Pick object instead of Partial, which works great if inlining your state object into the setState call, but prevents conditional construction of the state object to update.
Attempted code below, fails due to setState not taking a partial. newValue is a numeric parameter to the change handler function that this code excerpt is from.
const newState: Partial<localState> = {};
if (newValue !== 2) {
newState.settingA = null;
newState.settingTwo = null;
}
newState.multiCurrencyDynamicMode = newValue;
this.setState(newState);
I tried switching newState to const newState: Pick<localState, keyof localState>
but this fails due to this definition of pick expecting every key of localState to be present.
2
Answers
The definition for
Partial
is:So, without seeing how
localstate
is defined in your code, I’m guessing that it doesn’t allow undefined properties; but by usingPartial
, it’s effectively creating this as the type:Which is probably incompatible with your version of
localstate
. So, there’s two fixes you can choose:localstate
to optional – probably not what you want to do!Pick
and just list the keys you want to change, eg:In a class component with TypeScript, when you’re conditionally updating the state, you can indeed run into typing issues with TypeScript if your
setState
call doesn’t align with the expected type of your state.Here’s a pattern you can follow to ensure that TypeScript knows you’re providing a valid partial state update:
In this example, you start with an
update
object that has the mandatory update formultiCurrencyDynamicMode
. Then, based on your condition, you extend that update object with the additional keys (settingA
andsettingTwo
). Finally, you callthis.setState
with the update object.Since
this.setState
in React accepts a partial state update, this pattern should work correctly, and TypeScript should not complain as long as the keys in theupdate
object are valid keys from your state type (localState
in this case). This is because TypeScript understands thatPartial<localState>
is a type that can contain any subset of the properties oflocalState
.