Object property in store is reactive when adding but not when removing #2150
-
When I create a new store I can add properties to a nested object and the app is reactive to those changes. Things work as expected so far. However, when I start to delete or remove properties, even clearing it by setting it to an empty object, the store does not update nor is it reactive. Is this expected behaviour or is this a bug? I have a simple example on a fresh Solidjs project here: Add rows by clicking the button. By clicking on the rows it should be removing them. const App: Component = () => {
const [appState, setAppState] = createStore<AppState>({
id: "",
name: "",
data: {
states: {},
},
});
return (
<div class={styles.App}>
<AppForm app={appState} setApp={setAppState} />
</div>
);
};
export default App; app-form.tsx interface AppFormProps {
app: AppState;
setApp: SetStoreFunction<AppState>;
}
export const AppForm: Component<AppFormProps> = (props) => {
const dataStates = createMemo(() => {
console.log("State updated", props.app.data.states);
return Object.keys(props.app.data.states).map((stateId) => {
return {
id: stateId,
value: props.app.data.states[stateId],
};
});
});
const onAdd = () => {
const id = Math.random().toString(36).substring(7);
props.setApp("data", "states", id, "new");
};
const onRemove = (id: string) => () => {
console.log("Remove", id);
const newStates = { ...props.app.data.states };
delete newStates[id];
props.setApp("data", "states", { ...newStates });
};
return (
<div>
<h1>App Form</h1>
<button onClick={onAdd}>Add</button>
<ul>
<Index each={dataStates()}>
{(state) => <li onClick={onRemove(state().id)}>{state().value}</li>}
</Index>
</ul>
</div>
);
}; // this is in another file
export interface AppState {
id: string;
name: string;
data: {
states: {
[key: string]: string;
};
};
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
So far the solution to this has been to use an array to store records that you add/remove instead of a key/value object pair. But, I just want to know if using a |
Beta Was this translation helpful? Give feedback.
-
So apparently there is a way to remove record items in a store. This is briefly mentioned in the docs but it didn't show any examples: basically the fix is to use So the change should be the following: const onRemove = (id: string) => () => {
props.setApp("data", "states", id, undefined!);
}; |
Beta Was this translation helpful? Give feedback.
So apparently there is a way to remove record items in a store. This is briefly mentioned in the docs but it didn't show any examples:
https://www.solidjs.com/docs/latest/api#updating-stores
basically the fix is to use
undefined!
. (The!
is for typescript non-null assertion)So the change should be the following: