mobx#runInAction TypeScript Examples
The following examples show how to use
mobx#runInAction.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LanguageSwitcher.tsx From jmix-frontend with Apache License 2.0 | 7 votes |
LanguageSwitcher = observer((props: LanguageSwitcherProps) => {
const intl = useIntl();
const mainStore = useMainStore();
const handleChange = useCallback(
(locale: string) => runInAction(() => (mainStore.locale = locale)),
[mainStore]
);
if (localesStore.localesInfo.length === 1) {
return null; // Do not show LanguageSwitcher if there is only a single locale option
}
return (
<Select
defaultValue={mainStore.locale ?? undefined}
onChange={handleChange}
size="small"
style={props.style}
bordered={false}
className={props.className}
dropdownMatchSelectWidth={false}
aria-label={intl.formatMessage({ id: "a11y.select.LanguageSwitcher" })}
>
{localesStore.localesInfo.map(({ locale, caption }) => (
<Select.Option key={locale} value={locale}>
{caption}
</Select.Option>
))}
</Select>
);
})
Example #2
Source File: ClientsStore.ts From eth2stats-dashboard with MIT License | 6 votes |
@action.bound
fetch() {
return new Promise((resolve, reject) => {
axios.get(this.main.getNetworkConfig()!.HTTP_API + "/clients").then((response) => {
runInAction(() => {
this.updateList(response.data.data);
this.clientsLoading = false;
resolve();
});
}).catch((err) => {
reject(err);
});
});
}
Example #3
Source File: Collection.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
private handleLoadingWithCount(promise: Promise<EntitiesWithCount<T>>) {
return promise
.then((resp) => {
runInAction(() => {
this.items = fromRestModel<T>(resp.result, this.stringIdName ?? undefined);
this.count = resp.count;
this.status = 'DONE';
})
})
}
Example #4
Source File: Auth.ts From hive with MIT License | 6 votes |
@action
reconnect() {
const { authView, commonView } = this.store.viewModels;
const { mqttService } = this.store.services;
if (authView.lanType === LanType.lan) {
fetch(`${LOGIN_PATH}/local-auth`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(r => r.json())
.then(r => {
if (r.notLocal) {
runInAction(() => {
authView.authorized = false;
authView.lanType = LanType.wan;
commonView.loading = false;
});
} else {
runInAction(() => {
authView.authorized = true;
});
mqttService.setPassword(r.token);
}
})
.catch(() => {
setTimeout(() => {
this.loginLan();
}, 10000);
});
} else {
authView.authorized = false;
commonView.loading = false;
}
}
Example #5
Source File: NodeStatus.spec.tsx From lightning-terminal with MIT License | 6 votes |
describe('NodeStatus component', () => {
const render = () => {
return renderWithProviders(<NodeStatus />);
};
it('should display the Node Status label', () => {
const { getByText } = render();
expect(getByText('Node Status')).toBeInTheDocument();
});
it('should display the lightning balance', () => {
const { getByText, store } = render();
runInAction(() => {
store.nodeStore.wallet = {
channelBalance: Big(123),
walletBalance: Big(0),
confirmedBalance: Big(0),
};
});
expect(getByText('123 sats')).toBeInTheDocument();
});
it('should display the bitcoin balance', () => {
const { getByText, store } = render();
runInAction(() => {
store.nodeStore.wallet = {
channelBalance: Big(0),
walletBalance: Big(234),
confirmedBalance: Big(0),
};
});
expect(getByText('234')).toBeInTheDocument();
});
});
Example #6
Source File: store.ts From mysterium-vpn-desktop with MIT License | 6 votes |
loadConfig = async (): Promise<void> => {
const config = await tequilapi.userConfig()
runInAction(() => {
this.config = {
desktop: {},
...config.data,
}
log.info("Using config:", JSON.stringify(this.config))
})
runInAction(() => {
this.loaded = true
})
}
Example #7
Source File: local-state.tsx From nota with MIT License | 6 votes |
constructor(contents: string) {
this.contents = contents;
this.translation = this.tryTranslate();
makeAutoObservable(this);
let needsSync = false;
reaction(
() => [this.contents],
() => {
needsSync = true;
}
);
const SYNC_INTERVAL = 200;
setInterval(async () => {
if (needsSync) {
let translation = this.tryTranslate();
needsSync = false;
runInAction(() => {
this.translation = translation;
});
}
}, SYNC_INTERVAL);
}
Example #8
Source File: VoiceState.ts From revite with GNU Affero General Public License v3.0 | 6 votes |
// This imports and constructs the voice client.
@action async loadVoice() {
if (this.status !== VoiceStatus.UNLOADED) return;
this.status = VoiceStatus.LOADING;
try {
const { default: VoiceClient } = await import("./VoiceClient");
const client = new VoiceClient();
client.on("startProduce", this.syncState);
client.on("stopProduce", this.syncState);
client.on("userJoined", this.syncState);
client.on("userLeft", this.syncState);
client.on("userStartProduce", this.syncState);
client.on("userStopProduce", this.syncState);
runInAction(() => {
if (!client.supported()) {
this.status = VoiceStatus.UNAVAILABLE;
} else {
this.status = VoiceStatus.READY;
this.client = client;
}
});
} catch (err) {
console.error("Failed to load voice library!", err);
runInAction(() => {
this.status = VoiceStatus.UNAVAILABLE;
});
}
}
Example #9
Source File: Bots.ts From revolt.js with MIT License | 6 votes |
/**
* Edit a bot
* @param id Bot ID
* @param data Bot edit data object
*/
async edit(id: string, data: DataEditBot) {
await this.client.api.patch(`/bots/${id as ''}`, data);
if (data.name) {
const user = this.client.users.get(id);
if (user) {
runInAction(() => {
user!.username = data.name!;
});
}
}
}
Example #10
Source File: ContentStore.ts From Cleanarr with MIT License | 6 votes |
@action
async ignoreContent(contentKey: string): Promise<any> {
return new Promise((resolve, reject) => {
ignoreMedia(contentKey)
.then(() => {
for (let i = 0; i < this.content.length; i++) {
if (this.content[i].key === contentKey) {
const item = {
...this.content[i],
ignored: true,
}
runInAction(() => {
console.log(item);
this.content.splice(i, 1, item);
});
break;
}
}
resolve();
}).catch((error) => {
reject(error);
});
})
}
Example #11
Source File: files.ts From nebula-studio with Apache License 2.0 | 6 votes |
deleteFile = async (name: string) => {
const res: any = await service.deteleFile({
filename: name,
});
if (res.code === 0) {
message.success(intl.get('common.deleteSuccess'));
runInAction(() => {
this.fileList = this.fileList.filter((item) => item.name !== name);
});
}
};
Example #12
Source File: demo-mode-panel.tsx From ya-webadb with MIT License | 6 votes |
constructor() {
makeAutoObservable(this);
reaction(
() => GlobalState.device,
async (device) => {
if (device) {
runInAction(() => this.demoMode = new DemoMode(device));
const allowed = await this.demoMode!.getAllowed();
runInAction(() => this.allowed = allowed);
if (allowed) {
const enabled = await this.demoMode!.getEnabled();
runInAction(() => this.enabled = enabled);
}
} else {
this.demoMode = undefined;
this.allowed = false;
this.enabled = false;
this.features.clear();
}
},
{ fireImmediately: true }
);
// Apply all features when enable
autorun(() => {
if (this.enabled) {
for (const group of FEATURES) {
for (const feature of group) {
feature.onChange(this.features.get(feature.key) ?? feature.initial);
}
}
}
});
}
Example #13
Source File: observer.ts From aria-devtools with MIT License | 6 votes |
private onMutation = (mutations: MutationRecord[]) => {
runInAction("mutation", () => {
for (const mutation of mutations) {
if (this.getAomNode(mutation.target)) {
const target = mutation.target as HTMLElement;
if (
mutation.type === "attributes" &&
mutation.oldValue === target.getAttribute(mutation.attributeName ?? "")
) {
continue;
}
this.updateNode(mutation.target);
}
}
this.batchUpdate();
});
};
Example #14
Source File: useCalendar.tsx From jmix-frontend with Apache License 2.0 | 5 votes |
export function useCalendar<
TEntity = unknown,
TData extends Record<string, any> = Record<string, any>,
TQueryVars extends ListQueryVars = ListQueryVars,
TMutationVars extends HasId = HasId
>(
options: CalendarHookOptions<TEntity, TData, TQueryVars, TMutationVars>
): CalendarHookResult<TEntity, TData, TQueryVars, TMutationVars> {
const {
entityName,
eventStartDayPropertyName,
eventEndDayPropertyName,
eventTitlePropertyName,
eventDescriptionPropertyName,
} = options;
const entityListData = useEntityList<TEntity, TData, TQueryVars, TMutationVars>({...options, paginationConfig: {}});
const { entityListState, items } = entityListData;
const [currentMonthDayjs, setCurrentMonthDayjs] = useState(dayjs());
const {entities} = useMetadata();
const events = useMemo(() =>
items?.map(mapperItemToEvent({
entityName,
eventStartDayPropertyName,
eventEndDayPropertyName,
eventTitlePropertyName,
eventDescriptionPropertyName,
})
), [
entityName,
eventStartDayPropertyName,
eventEndDayPropertyName,
eventTitlePropertyName,
eventDescriptionPropertyName,
items,
]);
useEffect(() => {
const startPropInfo = getPropertyInfo(entities, entityName, eventStartDayPropertyName as string);
const endPropInfo = getPropertyInfo(entities, entityName, eventEndDayPropertyName as string);
const startDateBorder = dayjs(currentMonthDayjs.startOf('month')).subtract(2, 'week');
const endDateBorder = dayjs(currentMonthDayjs.endOf('month')).add(2, 'week');
runInAction(() => {
// Set filters for getting entities at end of previous month (-2 weeks), at current month, and at start of next month (+2 weeks)
entityListState.filter = [
{[eventStartDayPropertyName]: {_gte: applyDataTransferFormat(startDateBorder, startPropInfo?.type as TemporalPropertyType)}},
{[eventEndDayPropertyName]: {_lte: applyDataTransferFormat(endDateBorder, endPropInfo?.type as TemporalPropertyType)}}
];
});
}, [currentMonthDayjs, entities, entityListState, entityName, eventEndDayPropertyName, eventStartDayPropertyName]);
const handleCalendarPaginationChange = setCurrentMonthDayjs;
return {
...entityListData,
currentMonthDayjs,
setCurrentMonthDayjs,
handleCalendarPaginationChange,
events,
};
}
Example #15
Source File: Mqtt.ts From hive with MIT License | 5 votes |
connect(token: string) {
const { commonView, authView, mqttView } = this.store.viewModels;
const { authService } = this.store.services;
if (this.client) {
this.client.options.password = token;
return;
}
this.client = mqtt.connect(MQTT_PATH, {
username: 'anyuser',
clientId: this.clientId,
password: token,
keepalive: 60,
connectTimeout: 30000,
clean: true,
});
this.client.on('close', () => {
runInAction(() => {
if (authView.authorized) {
commonView.setLoadingText('Connection with server lost...');
commonView.loading = true;
}
});
});
this.client.on('error', () => {
runInAction(() => {
authService.reconnect();
setTimeout(() => {
if (commonView.loading) {
window.location.reload();
}
}, 5000);
});
});
this.client.on('connect', () => {
runInAction(() => {
if (!mqttView.initialized) {
mqttView.initialized = true;
}
authView.loading = false;
commonView.loading = false;
});
});
this.client.on('message', (topic: string, message: Buffer) => {
const messageResult = JSON.parse(message.toString());
if (messageResult.clientId !== this.clientId && messageResult.clientId != null) return;
delete messageResult.clientId;
const subscription = this.subscriptions.get(topic);
if (subscription) {
subscription.forEach(x => {
runInAction(() => {
x(messageResult);
});
});
}
});
}
Example #16
Source File: index.ts From hubble-ui with Apache License 2.0 | 5 votes |
private listen() {
this.history.listen(({ location }) => {
runInAction(() => (this.location = location));
});
}
Example #17
Source File: VsCodeSetting.ts From vscode-drawio with GNU General Public License v3.0 | 5 votes |
workspace.onDidChangeConfiguration(() => {
runInAction("Update Configuration", () => {
VsCodeSettingResource.onConfigChange.emit();
});
});
Example #18
Source File: AlertStore.ts From flood with GNU General Public License v3.0 | 5 votes |
scheduleClose(id: string, duration: number): number {
return window.setTimeout(() => {
runInAction(() => {
delete this.alerts[id];
});
}, duration);
}
Example #19
Source File: store.ts From react-gantt-component with MIT License | 5 votes |
/**
* 更新时间
*/
@action
async updateTaskDate(
barInfo: Gantt.Bar,
oldSize: { width: number; x: number },
type: 'move' | 'left' | 'right' | 'create'
) {
const { translateX, width, task, record } = barInfo;
const oldStartDate = barInfo.task.startDate;
const oldEndDate = barInfo.task.endDate;
let startDate = oldStartDate;
let endDate = oldEndDate;
if (type === 'move') {
const moveTime = this.getMovedDay(
(translateX - oldSize.x) * this.pxUnitAmp
);
// 移动,只根据移动距离偏移
startDate = dayjs(oldStartDate)
.add(moveTime, 'day')
.format('YYYY-MM-DD HH:mm:ss');
endDate = dayjs(oldEndDate)
.add(moveTime, 'day')
.format('YYYY-MM-DD HH:mm:ss');
} else if (type === 'left') {
const moveTime = this.getMovedDay(
(translateX - oldSize.x) * this.pxUnitAmp
);
// 左侧移动,只改变开始时间
startDate = dayjs(oldStartDate)
.add(moveTime, 'day')
.format('YYYY-MM-DD HH:mm:ss');
} else if (type === 'right') {
const moveTime = this.getMovedDay(
(width - oldSize.width) * this.pxUnitAmp
);
// 右侧移动,只改变结束时间
endDate = dayjs(oldEndDate)
.add(moveTime, 'day')
.format('YYYY-MM-DD HH:mm:ss');
} else if (type === 'create') {
//创建
startDate = dayjs(translateX * this.pxUnitAmp).format(
'YYYY-MM-DD HH:mm:ss'
);
endDate = dayjs((translateX + width) * this.pxUnitAmp)
.subtract(1)
.hour(23)
.minute(59)
.second(59)
.format('YYYY-MM-DD HH:mm:ss');
}
if (startDate === oldStartDate && endDate === oldEndDate) {
return;
}
runInAction(() => {
barInfo.loading = true;
});
const success = await this.onUpdate(record, startDate, endDate);
if (success) {
runInAction(() => {
task.startDate = startDate;
task.endDate = endDate;
});
} else {
barInfo.width = oldSize.width;
barInfo.translateX = oldSize.x;
}
}
Example #20
Source File: VsCodeSetting.ts From vscode-lean4 with Apache License 2.0 | 5 votes |
workspace.onDidChangeConfiguration(() =>
runInAction(() => VsCodeSettingResource.onConfigChange.fire(undefined)));
Example #21
Source File: AuthPage.spec.tsx From lightning-terminal with MIT License | 5 votes |
describe('AuthPage ', () => {
let store: Store;
beforeEach(async () => {
store = createStore();
await store.init();
});
const render = () => {
return renderWithProviders(<AuthPage />, store);
};
it('should display the title', () => {
const { getByText } = render();
expect(getByText('Lightning')).toBeInTheDocument();
expect(getByText('Terminal')).toBeInTheDocument();
});
it('should display the password field', () => {
const { getByLabelText } = render();
expect(getByLabelText('Enter your password in the field above')).toBeInTheDocument();
});
it('should display the submit button', () => {
const { getByText } = render();
expect(getByText('Submit')).toBeInTheDocument();
});
it('should display nothing when the store is not initialized', () => {
const { getByText, queryByText } = render();
expect(getByText('Lightning')).toBeInTheDocument();
expect(getByText('Terminal')).toBeInTheDocument();
runInAction(() => {
store.initialized = false;
});
expect(queryByText('Lightning')).not.toBeInTheDocument();
expect(queryByText('Terminal')).not.toBeInTheDocument();
});
it('should display an error when submitting an empty password', async () => {
const { getByText, findByText } = render();
fireEvent.click(getByText('Submit'));
expect(await findByText('oops, password is required')).toBeInTheDocument();
});
it('should display an error when submitting an invalid password', async () => {
grpcMock.unary.mockImplementationOnce(desc => {
if (desc.methodName === 'GetInfo') throw new Error('test-err');
return undefined as any;
});
const { getByText, getByLabelText, findByText } = render();
const input = getByLabelText('Enter your password in the field above');
fireEvent.change(input, { target: { value: 'test-pw' } });
fireEvent.click(getByText('Submit'));
expect(await findByText('oops, that password is incorrect')).toBeInTheDocument();
});
});
Example #22
Source File: store.ts From mysterium-vpn-desktop with MIT License | 5 votes |
setGracePeriod = (): void => {
this.gracePeriod = true
setTimeout(() => {
runInAction(() => {
this.gracePeriod = false
})
}, 5000)
}