简体   繁体   中英

ExpressJS/NextJS front-end/back-end issues

I have 2 GitHub repos, one for frontend, one for backend. My backend is using Express JS and is handling an axios call to fetch some data, that part is fine. My frontend is built with NextJS. I'm trying to create a useQuery call to grab the data from my backend server but am strugging. Here is my backend code: https://i.stack.imgur.com/dbW2y.jpg

How would i structure the front-end NextJS to then connect and grab that data for my front-end? If i had one single repository i wouldn't have much of an issue with this, but having them seperated is causing me some troubles! Thanks in advance, sorry if this isn't well explained!

import React from 'react';
import { useQuery } from 'react-query'

const fetchDataListFromAPI = async () => {
    //Call your api, in your example https://myserver/myendpoint
    const res = await fetch('https://swapi.dev/api/people/');
    return res.json();
}

export default function DataList() {
    const { data, status } = useQuery("people", fetchDataListFromAPI);
    //Check your data
    console.log("data",data);
    //check de status fetch
    console.log("status",status);
    //Return your template
    return (
        <>
            <div>
             {
                status==="success" &&
                data.results.map((item)=>...)
             }
            </div>
        </>
    );
}

I explain the above code:

I use useQuery to search for data. useQuery accepts two parameters, the first is the key and the second is the asynchronous function that gets data from the API. In returns, the useQuery hooks return two values. One is the data and the other is the state. The statuses are "Success", "Error", "Loading". Fetch always returns promises, so it's a good idea to use async/await for the async method.

I'm using starwar api to fetch data using useQuery.

Note: I suggest you give your endpoint a name and follow the guide for defining enpoint names for your rest api

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM