Friday, December 31, 2021

Loading data asynchronously with Vue and Pinia

When working with Vue 3 Composition API and Pinia, I struggled a bit to put out an example of loading async data, where the request is handled by the Pinia store, which also owns the data.

It’s 2 AM and, finally, here is the store:

import {ref, reactive} from 'vue';
import {defineStore} from 'pinia';

const useStore = defineStore('fruits', () => {
	const fruits = reactive<string[]>([]);
	const loading = ref(false);

	return {
		fruits,
		loading,
		loadFruits(): Promise<void> {
			loading.value = true;
			return new Promise((resolve, _reject) => {
				setTimeout(() => {
					fruits.push('lemon', 'orange', 'peach', 'strawberry');
					loading.value = false;
					resolve();
				}, 2000);
			});
		},
	};
});

export default useStore;

And this is the single file component, which calls the store asynchronously:

<template>
	<div v-if="loading">Loading...<div>
	<div v-if="!loading">
		<div v-for="fruit of fruits" :key="fruit">
			{{fruit}}
		</div>
	</div>
</template>

<script setup lang="ts">
import {computed, onMounted} from 'vue';
import useStore from '@/model/store';

const store = useStore();
const loading = computed(() => store.loading);
const fruits = computed(() => store.fruits);

onMounted(() => {
	store.loadFruits();
});
</script>

Although I’m not seeing much advantage of Vue over React, Pinia is so much better than Redux insanity. Even with Redux Toolkit. I hope they don’t mess it up when Pinia becomes Vuex 5, as said.

Tuesday, December 28, 2021

Two-way binding input in React

As a follow-up to my big disappointment with Vue due to the lack of typed emits, even with TypeScript, I came back to think about a two-way binding input in React. Turns out, it’s pretty trivial to implement.

import { useState } from 'react';
	
interface TwoWayValue {
	value: string;
	setValue: (value: string) => void;
}

interface Props {
	data: TwoWayValue;
}

function TwoWayInput(props: Props) {
	return <input type="text" value={props.data.value}
		onChange={e => props.data.setValue(e.target.value)} />;
}

function useTwoWayState(initialValue: string): TwoWayValue {
	const [value, setValue] = useState(initialValue);
	return { value, setValue };
}

export { TwoWayValue, TwoWayInput, useTwoWayState };

Usage:

import { TwoWayInput, useTwoWayState } from 'two-way-input';

function App() {
	const nome = useTwoWayState('');

	return <div>
		<h1>{nome.value}</h1>
		<TwoWayInput type="text" data={nome} />
	</div>;
}

Now I’m still wondering about scoped CSS.

Tuesday, December 14, 2021

Install and uninstall Rust nightly

When developing the full-module refactoring of WinSafe, I found that it’s possible to tag the items with their respective required Cargo features. However, as many things in Rust, this is still available only in the nightly toolchain.

I want to make WinSafe available for the stable toolchain, so I needed to install nightly just to see how that stuff worked out, and then uninstall it after the tests.

Rust nightly can be installed and uninstalled with the following commands:

rustup install nightly
rustup toolchain remove nightly

To see which toolchains are installed:

rustup show

Thursday, December 2, 2021

RAII guards in Rust

While experimenting with scope rules in Rust, I ended up implementing a recurrent idea I had – a RAII guard that runs a function when the object goes out of scope. I’m well aware of scopeguard crate, but it has some stinky unsafe bits in its implementation.

I was never able to properly implement it, probably because my Rust skills weren’t good enough, but now I did. And I’m rather satisfied with it:

use std::ops::Deref;

/// Returns the object wrapped in a way that the associated closure will run
/// when it goes out of scope.
pub struct Guard<T, D: FnOnce(&mut T)> {
	asset: T,
	dropper: Option<D>,
}

impl<T, D: FnOnce(&mut T)> Drop for Guard<T, D> {
	fn drop(&mut self) {
		self.dropper.take()
			.map(|d| d(&mut self.asset));
	}
}

impl<T, D: FnOnce(&mut T)> Deref for Guard<T, D> {
	type Target = T;

	fn deref(&self) -> &Self::Target {
		&self.asset
	}
}

impl<T, D: FnOnce(&mut T)> Guard<T, D> {
	/// Creates a new `Guard` object.
	pub fn new(asset: T, dropper: D) -> Guard<T, D> {
		Self { asset, dropper: Some(dropper) }
	}
}

I though about writing stuff like this in WinSafe:

impl HWND {
	pub fn GetDC(self) -> WinResult<Guard<HDC, impl FnOnce(&mut HDC)>> {
		Ok(Guard::new(
			self.GetDC()?,
			move |hdc| {
				self.ReleaseDC(*hdc).expect("Guard crash.");
			},
		))
	}
}

But then there are big implications like CreateMenu, which may or may not require a DestroyMenu call. These dubious behaviors are very unsettling, and many questions arise:

  • Should I write another method, with a _guarded suffix?
  • Mark the unguarded original as unsafe?
  • In the example above, self is copied into the closure – what if it’s still zero?

So by now I believe I’ll leave everything as it is, and let the defer-lite crate at hand when needed.

Still, I greatly miss the idiomatic defer in Go.