简体   繁体   中英

How to get data using async await?

How to get the data correctly

import { NextApiHandler } from "next";
import data from "../../../lib/data.json";

const cars: NextApiHandler = (_req, res) => {
  res.status(200).json(data);
};

export default cars;

I tried to use async await for getting data but something went wrong. When I`m trying to print in console.log what is "cars" it returns me function instead of promise.

You can try this way to get data

import React, { useEffect, useState } from 'react';

import Item from '../Item/Item';


const Items = () => {
    const [items, setItems] = useState([]);
     
    useEffect( ()=>{
     fetch('http://localhost:5000/items') 
     .then(res => res.json())
     .then(data => setItems(data));  
    }, [])
    return (
        <div id='items' className='container'>
            <h1 className='item-title'>Items For You</h1>
            <div className="items-container">
            {
                items.map(item => <Item
                key={item._id}
                item={item}
                >
                </Item>)
            }
            </div>
        </div>
    );
};

export default Items;

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