#Problem with debouncing mechanism with nextjs 14

3 messages · Page 1 of 1 (latest)

loud ermine
#

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?

'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!!

honest sigilBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

summer slate
#

try with keyUp event instead keyDown