Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Async autocomplete example #84

Closed
Fronix opened this issue Nov 6, 2019 · 3 comments · Fixed by #88
Closed

[Question] Async autocomplete example #84

Fronix opened this issue Nov 6, 2019 · 3 comments · Fixed by #88

Comments

@Fronix
Copy link

Fronix commented Nov 6, 2019

I'm looking to implement SWR in a project but I'm wondering if it would be beneficial to use this for a type of async autocomplete component and if so how would that look, all the current examples are based on that you have static data that you get when rendering but how would it look when you have data you want to load based on what you type like a autocomplete?

@sergiodxa
Copy link
Contributor

You could fetch data based on a dynamic value, check dependant fetching in the README.

If you have a state with your typed value you could:

const [value, setValue] = useState(null) // the null here will prevent SWR to fetch until the user typed something
const { data: results } = useSWR(() => `/api/search?query=${value}`, fetcher)

Now every time the value state change SWR will fetch the /api/search with a new query, if the user delete a character of the value (e.g. from movies to movie) since SWR already fetched that it will show the stale results immediately.

And you could use your results to fill the autocomplete suggestions.

@Fronix
Copy link
Author

Fronix commented Nov 6, 2019

Interesting!

I tried this just now

  const [value, setValue] = useState<null | string>(null);
  const { data: results } = useSWR(
    () => `/api/search/autocomplete/${entity}/?query=${value}`,
    (url: string) => fetch(url).then(_ => _.json())
  );

Still triggers the fetch when the value is null also the result is sometimes undefined when deleting a character which also is a bit weird? Might be some missing options?

@shuding
Copy link
Member

shuding commented Nov 6, 2019

Hi @Fronix !

I've created an example for this use case: https://codesandbox.io/s/swr-playground-3843q

Still triggers the fetch when the value is null

The entire key needs to be null, e.g.:

  useSWR(value ? `/api/search/autocomplete/${entity}/?query=${value}` : null, ...)

the result is sometimes undefined when deleting a character

That's because the key has changed, so the data for that new key will be undefined until we get the data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants