Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading