Problem with debouncing mechanism with nextjs 14
Unanswered
Transvaal lion posted this in #help-forum
Transvaal lionOP
I'm working with the fake api jsonplaceholder. I'm listing posts and trying to filter them by userID, changing the endpoint. To avoid hitting the api many times, I wanted to make a debounce mechanism.
I'm using a dynamic url which changes when the user inputs and ID in a number input. For fetching data i'm using the hook useSWR, and for revalidating the data when the user wants to filter it, I'm using mutate of SWR.
The debounced mechanism works well but the only problem is that is one character delayed. For example, if the user types the ID 11, it only takes the first number, 1. The first user input doesn't make any effect for this reason.
Any idea of how can I solve this?
It continues but it's just how I handle some errors and the HTML Code.
Thanks!!
I'm using a dynamic url which changes when the user inputs and ID in a number input. For fetching data i'm using the hook useSWR, and for revalidating the data when the user wants to filter it, I'm using mutate of SWR.
The debounced mechanism works well but the only problem is that is one character delayed. For example, if the user types the ID 11, it only takes the first number, 1. The first user input doesn't make any effect for this reason.
Any idea of how can I solve this?
'use client'
import { useEffect, useState } from "react";
import Cards from "../components/Cards";
import useSWR, { useSWRConfig } from "swr";
import { useDebounce } from 'use-debounce';
const fetcher = async (url: string) => {
const res = await fetch(url)
const data = await res.json()
return data
}
export default function Page(){
const [val, setVal] = useState("")
const [url, setUrl] = useState('https://jsonplaceholder.typicode.com/posts');
const [debounced] = useDebounce(val, 1000)
const {data, error} = useSWR('/posts', () => fetcher(url))
const { mutate } = useSWRConfig()
const change = (event: any) => {
setVal(event.target.value)
if(val != '') setUrl(`https://jsonplaceholder.typicode.com/posts?userId=${Number(val)}`)
else setUrl('https://jsonplaceholder.typicode.com/posts')
}
useEffect(() => {
mutate('/posts')
console.log(url)
}, [debounced])It continues but it's just how I handle some errors and the HTML Code.
Thanks!!
2 Replies
Spectacled bear
try with keyUp event instead keyDown
@Spectacled bear try with keyUp event instead keyDown
Transvaal lionOP
hey it actually worked!!! thanks a lot!!â¤ï¸ :DD