S
SolidJS•13mo ago
oneiro

Prefill Input with value from a fetch source - Best practice

Hey folks, I am currently trying to prefill an input field with saved user values. I have basically two things I would like to combine: 1. I have a resource which asynchronously fetches the saved user value of the input 2. I have a signal inside the component which is used for the controlled input of the value Basically what should happen is: - The user starts the app - If they already have a saved value for the respective input, the input should be prefilled with that value - Otherwise it should be empty - When they type into the input their changes should be reflected accordingly I've read that filling the signal with a createEffect when the resource is available is discouraged (which makes sense) and therefore opted for createMemo. I have a working solution (see code below), but my question: is there a better more idiomatic way to achieve this? Here is my current (simplified) solution:
const [valueFromStore, { refetch }] = createResource(loadValue)

function SomeForm() {
const [inputValue, setInputValue] = createSignal<string>('')

const handleInputChange = (event) => setInputValue(event.target.value)

const valueFromStoreOrInput = createMemo(() => {
if (valueFromStore.loading) {
return 'loading'
}

return inputValue().length > 0 ? inputValue() : valueFromStore() ?? ''
})
}
const [valueFromStore, { refetch }] = createResource(loadValue)

function SomeForm() {
const [inputValue, setInputValue] = createSignal<string>('')

const handleInputChange = (event) => setInputValue(event.target.value)

const valueFromStoreOrInput = createMemo(() => {
if (valueFromStore.loading) {
return 'loading'
}

return inputValue().length > 0 ? inputValue() : valueFromStore() ?? ''
})
}
Thanks in advance 🙂
0 Replies
No replies yetBe the first to reply to this messageJoin