Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

reactjs - Next js send id to API route on click and fetch result

When I click on a button inside a component I send back to the Page an id via function const readUrl, now I'm trying to send client-side that id to an /api/dat/[id].js route where inside it basically searches for that id within mongodb and res.send back to the Page the JSON result.

So via SWR, I'm dealing with the API route client-side and I use two useState to deal with id from a button click and result from API to pass it to the react DOM

The issue is I get Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

this is my api/dat/[id].js:

import { connectToDatabase } from "../../utils/mongodb"
    
export default async function ({ query: { id } }, res) {   
    const { db } = await connectToDatabase();
    const dataID = id

    const foundData = /* query to mongodb.toArray() */

    if (foundData.length) {
        res.status(200).send({ data: foundData[0] })
    } else {
        res.status(404).json({ message: `Data ${id} not found.` })
    }
    
    res.end()
}

this is the code in my page:

const [urlNow, setUrlNow] = useState(null);
const [urlData, setUrlData] = useState(null);

const readUrl = (url) => {
  setUrlNow(url)
  return true
}

const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR(readUrl ? `/api/dat/${urlNow}` : null, fetcher)

// if (error) return <div>{error.message}</div>
// if (!data) return <div>Loading...</div>
if (data) setUrlData(data.data)

return (
     ...
       {urlData
          ? <Component data={urlData} />
          : <ComponentWithButton readUrl={readUrl} />
       }

useSWR as it is set above fires up only if function readUrl returns true, as SWR docs say, so I think it should fetch the API route only if the button gets clicked, at least that was the idea.

question from:https://stackoverflow.com/questions/65848065/next-js-send-id-to-api-route-on-click-and-fetch-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding an answer for the sake of leaving a full solution to the issue mentioned in the comments.

You should replace the condition in useSwr() to use urlNow rather than the readUrl function. Some states/variables can also be cleaned up to make the code simpler.

const [urlNow, setUrlNow] = useState(null);

const readUrl = (url) => {
    setUrlNow(url)
}

const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR(urlNow ? `/api/dat/${urlNow}` : null, fetcher)

// if (error) return <div>{error.message}</div>
// if (!data) return <div>Loading...</div>

return (
    {data
        ? <Component data={data} />
        : <ComponentWithButton readUrl={readUrl} />
    }
    //...
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...