Save changes in settings when unmounting (#1152)

## Description

Save changes in settings when unmounting e.g. when switiching to another
tab

## Steps for reproduction

1. change instance name in settings
2. switch to another tab
3. should save

## Code Review

- [ ] hi @rpominov , I need you to do
  - conceptual review (architecture, feature-correctness)
  - detailed review (read every line)
  - test it on preview

## Before requesting a review

- [ ] made a self-review
- [ ] added inline comments where things may be not obvious (the "why",
not "what")

## Before merging

- [ ] tested locally and on preview environment (preview dev login:
5de6)
- [ ] updated [test
cases](https://github.com/webstudio-is/webstudio-builder/blob/main/apps/builder/docs/test-cases.md)
document
- [ ] added tests
- [ ] if any new env variables are added, added them to `.env.example`
and the `builder/env-check.js` if mandatory
This commit is contained in:
Oleg Isonen authored and GitHub committed 2023-03-01 13:57:56 +01:00
1 parent 42cbd5eabc
commit dd7bcba787
1 file changed
+11 -3
@@ -1,6 +1,11 @@
import type { Instance } from "@webstudio-is/project-build";
import store from "immerhin";
import { type KeyboardEventHandler, useRef } from "react";
import {
type KeyboardEventHandler,
useRef,
useEffect,
useCallback,
} from "react";
import { instancesStore } from "~/shared/nano-states";
type SettingUpdate = { label?: string };
@@ -17,14 +22,14 @@ export const useSettingsLogic = ({
changes.current.label = value || undefined;
};
const updateLabel = () => {
const updateLabel = useCallback(() => {
store.createTransaction([instancesStore], (instances) => {
const instance = instances.get(selectedInstance.id);
if (instance !== undefined) {
instance.label = changes.current.label;
}
});
};
}, [selectedInstance]);
const handleKeyDown: KeyboardEventHandler = (event) => {
if (event.key === "Enter") {
@@ -32,6 +37,9 @@ export const useSettingsLogic = ({
}
};
// Save changes when unmounting, e.g. when switiching to another tab
useEffect(() => updateLabel, [updateLabel]);
return {
setLabel,
handleBlur: updateLabel,