SolidJSS
SolidJSโ€ข5mo agoโ€ข
9 replies
Seb

Input focus problem when trying to retrieve data with createAsync

I have the following code where I try to call a server function based on the content of an input. The goal is to retrieve a list of cities based on the entered zip code.

My problem with this code is that each type I type something in the input, it looses the focus.

I found several information about input loosing focus because the input is recreated but I don't think I am in this case. I can't figure out the problem here.

import { createStore } from 'solid-js/store';
import { createAsync, query } from '@solidjs/router';
import { For } from 'solid-js';

type SearchFields = {
  zipCode?: string;
};

const getCities = query(async (zipCode?: string) => {
  if (!zipCode || zipCode.length !== 5) return undefined;
  return [{ name: "test" }];
}, "getCities");

export default function Root() {
  const [searchFields, setSearchFields] = createStore<SearchFields>();
  const citiesByZipCode = createAsync(() => getCities(searchFields.zipCode));

  createEffect(() => console.log("citiesByZipCode", citiesByZipCode()));
  return (
    <form method="post">
      <fieldset>
        <legend>Code postal</legend>
        <input oninput={(event) => setSearchFields({ zipCode: event.target.value })} />
        <For each={citiesByZipCode()}>{(city) => <div>{city.name}</div>}</For>
      </fieldset>
    </form>
  )
}
Was this page helpful?