Below is my code to get data from an API and display on my server, the data comes in but does not display on the screen :
const express = require('express');
const router = express.Router();
const data = require('../data');
const peopleData = data.people;
router.get('/', async (req, res) => {
try {
const peopleList = await peopleData.getPeople();
res.render('people/user',{peopleList:peopleList});
} catch (e) {
res.status(500).send();
}
});
module.exports = router;
Data function:
require("util").inspect.defaultOptions.depth = null;
const axios = require('axios');
async function getPeople(){
const { data } = await axios.get('https://gist.githubusercontent.com/SwayamShah97/0f2cb53ddfae54eceea083d4aa8d0d65/raw/d7d89c672057cf7d33e10e558e001f33a10868b2/people.json');
return data; // this will be the array of people objects
}
module.exports = {
getPeople
}
Handlebars:
<div>
<table>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
{{#each peopleList}}
<tr>
<td>{{id}}</td>
<td>{{firstName}}</td>
<td>{{lastName}}</td>
</tr>
{{/each}}
</table>
</div>
Not sure why nothing displays, I console log and the data comes in fine.
Related
I am beginner of React and node js. When we fetch data from the data and pass into the table. I got this error
Uncaught TypeError: employees.map is not a function
I tested the code from the postman it is working fine.
In order to connect to the React ran into problem. What I tried so far I attached below.
<table class="table table-dark" align="center">
<thead>
<tr>
<th scope="col">Employee Id</th>
<th scope="col">Employee Name</th>
<th scope="col">Employee Address</th>
<th scope="col">Employee Mobile</th>
<th scope="col">Option</th>
</tr>
</thead>
{employees.map(function fn(employee)
{
return(
<tbody>
<tr>
<th scope="row">{employee._id} </th>
<td>{employee.name}</td>
<td>{employee.address}</td>
<td>{employee.phone}</td>
<td>
<button type="button" class="btn btn-warning" onClick={() => editEmployee(employee)} >Edit</button>
<button type="button" class="btn btn-danger" onClick={() => DeleteEmployee(employee._id)}>Delete</button>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
);
}
import axios from 'axios';
import {useEffect, useState } from "react";
function CustomerCrud()
{
const [_id, setId] = useState('');
const [name, setName] = useState("");
const [address, setAddress] = useState("");
const [phone, setMobile] = useState("");
const [employees, setUsers] = useState([]);
useEffect(() => {
(async () => await Load())();
}, []);
async function Load()
{
const result = await axios.get(
"http://localhost:8000/user/getAll");
setUsers(result.data);
console.log(result.data);`
}
Console Format
Object
data
:
Array(1)
0
:
address
:
"indiafabiiii"
name
:
"kobi"
phone
:
"53423332"
__v
:
0
_id
:
"63a3d39df8a99b15db6eb9f6"
[[Prototype]]
:
Object
length
:
1
[[Prototype]]
:
Array(0)
status
:
true
Postman
{
"status": true,
"data": [
{
"_id": "63a3d39df8a99b15db6eb9f6",
"name": "kobi",
"address": "indiafabiiii",
"phone": "53423332",
"__v": 0
}
]
}
Axios return data in the data object. So, you have to get an array by two-time destructuring. result.data.data
import axios from 'axios';
import {useEffect, useState } from "react";
function CustomerCrud()
{
const [_id, setId] = useState('');
const [name, setName] = useState("");
const [address, setAddress] = useState("");
const [phone, setMobile] = useState("");
const [employees, setUsers] = useState([]);
useEffect(() => {
(async () => await Load())();
}, []);
async function Load()
{
const result = await axios.get(
"http://localhost:8000/user/getAll");
setUsers(result.data.data);
console.log(result.data);`
}
here i am fetching data from API which is giving me response in "array of objects" i want to store it in the array called products and want to display it on the page.
Here is my code
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
const AllProduct = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
);
console.log(data.response);
setProducts(data.response);
console.log(products);
};
const display = () => {
return (products ?? []).map(product => (
<tr key={product.id}>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>
) );
}
useEffect(() => {
fetchProducts();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Area</th>
<th>Owner Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
{display()}
</tbody>
</table>
</div>
)
}
export default AllProduct;
I have used ReactJS for frontend and NodeJS
here is the screenshot of what i am getting on console
Check that the type of products is array. If it is an object, an error occurs.
I am trying to fetch data from backend, I want to load all data which are in database, when I load function then getting an error like "User.map is not a function", please let me know where am wrong.
User.js
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { getUsers } from "./apis";
const UserData = () => {
const [users, setUser] = useState([]);
useEffect(() => {
AllUsers();
}, []);
const AllUsers = async () => {
const response = await getUsers();
console.log(response.data);
setUser(response.data ? response.data : []);
};
return (
<div>
<div className="container">
<table className="table table-hover table-bordered mt-5">
<thead>
<tr>
{/* <th scope="col">No</th> */}
<th scope="col">Title</th>
<th scope="col">Details</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={index}>
<th scope="row">{user.id}</th>
<td>{user.title}</td>
<td>{user.description}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
};
Api.js
I have added api.js file please check it , and let me know where am wrong
export default UserData;
import Axios from "axios";
const url = "http://localhost:3000/";
export const getUsers = async (id) => {
id = id || "";
return await Axios.get(`${url}/${id}`);
};
export const deleteUser = async (id) => {
return await Axios.delete(`${url}/${id}`);
};
You can use Optional chaining (?.) for check the data is available or not. Because while API's is calling data not set in your state. It's might be a undefined.
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
In your case do with this way.
{users?.map((user, index) => (
<tr key={index}>
<th scope="row">{user.id}</th>
<td>{user.title}</td>
<td>{user.description}</td>
</tr>
))}
import Axios from "axios";
const url = "http://localhost:3000/";
export const getUsers = async (id) => {
id = id || "";
return await Axios.get(`${url}/${id}`);
};
export const deleteUser = async (id) => {
return await Axios.delete(`${url}/${id}`);
};
I've looked around on the web for solutions but there doesn't seem to be an answer relevant to mine. So I would like some help on this, please. Here I have two tables I need to connect and list on the React file. game table and users table, at the moment I am only able to display game table.
Server/index.js
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
//middleware
app.use(cors());
app.use(express.json()); //req.body
app.get("/af", async (req, res) => {
try {
const allTodos = await pool.query("SELECT game.*, users.* FROM users INNER JOIN game ON users.game_code = game.game_code; ");
res.json(allTodos.rows);
} catch (err) {
console.error(err.message);
}
});
Client/List.js
const List = () => {
const [af, setAF] = useState([]);
const getTodos = async() => {
try{
const response = await fetch("http://localhost:5000/af");
const jsonData = await response.json();
setAF(jsonData);
}catch(err){
console.error(err.message);
}
}
useEffect(() => {
getTodos();
}, []);
return(
<Fragment>
{" "}
<table className="table mt-5 text-center">
<thead>
<tr>
<th>game_code</th>
<th>user_code</th>
</tr>
</thead>
<tbody>
{af.map(game => (
<tr key = {game.game}>
<td>{game.game_code}</td>
<td>{game.game_location}</td>
))}
</tbody>
</table>
</Fragment>
export default List;
The Problem: syntax error at or near "$"
The Context: My App does two CRUD operations - Update & Read Data from a Postgres database. It successfully reads data from the database and displays on the frontend. However, it fails to update the database when I query it to do so. It throws an error that 'syntax error at or near "$"'.
So far, I have failed to debug the error successfully.
The Stacks: Postgres, Node.js, React
The Query (BackEnd):
//burrow a book
app.post("/books/:id", async (req, res) => {
try {
const { id } = req.params;
const copies = await pool.query('SELECT copies FROM books WHERE book_id = $id', [id]);
const stock = copies - 1;
const updateBook = await pool.query("UPDATE books SET copies = $1 WHERE book_id = $2", [stock, id]);
const allBooks = await pool.query("SELECT * FROM books");
res.json(allBooks.rows);
} catch (err) {
console.error(err.message);
}
});
The Function(FrontEnd):
async function burrowbook(id) {
try {
const res = await fetch(`http://localhost:5000/books/${id}` , {method: "POST"});
console.log(res);
// setbooks(jsonData);
// console.log(jsonData);
} catch (err) {
console.error(err.message);
}
}
The Full React Component(FrontEnd):
import React, { Fragment, useEffect, useState } from 'react';
const ListBooks = () => {
const [books, setbooks] = useState([]);
async function burrowbook(id) {
try {
const res = await fetch(`http://localhost:5000/books/${id}` , {method: "POST"});
console.log(res);
// setbooks(jsonData);
// console.log(jsonData);
} catch (err) {
console.error(err.message);
}
}
const getBooks = async () => {
try {
const response = await fetch("http://localhost:5000/books");
const jsonData = await response.json();
setbooks(jsonData);
// console.log(jsonData);
} catch (err) {
console.error(err.message);
}
}
useEffect(() => {
getBooks();
}, []);
return (<Fragment>
<div class="container ">
<h1 class="text-center mt-5">Wakanda Library</h1>
</div>
<table class="table table-hover table-dark text-center mt-5">
<thead>
<tr>
<th scope="col">Book ID</th>
<th scope="col">Title</th>
<th scope="col">Author</th>
<th scope="col">Year</th>
<th scope="col">Stock</th>
<th scope="col">Burrow</th>
<th scope="col">Return</th>
</tr>
</thead>
<tbody>
{books.map(book => (
<tr key={book.book_id}>
<td>{book.book_id} </td>
<td>{book.title} </td>
<td>{book.author} </td>
<td>{book.publish_year} </td>
<td>{book.copies} </td>
<td><button
className="btn btn-success btn-circle btn-md"
onClick={() => burrowbook(book.book_id)}
>
Burrow
</button></td>
<td><button
className="btn btn-primary btn-circle btn-md"
// onClick={() => returnBook(book.book_id)}
>
Return
</button></td>
</tr>
))}
</tbody>
</table>
</Fragment>);
};
export default ListBooks;
The Full index.js script(BackEnd):
const express = require("express");
const app = express();
const cors = require('cors');
const pool = require('./db');
//middleware
app.use(cors());
app.use(express.json()); //req.body
//ROUTES//
//login user
//register user
//list of books in library
app.get("/books", async (req, res) => {
try {
const allBooks = await pool.query("SELECT * FROM books");
res.json(allBooks.rows);
} catch (err) {
console.error(err.message);
}
});
//burrow a book
app.post("/books/:id", async (req, res) => {
try {
const { id } = req.params;
console.log(id);
const copies = await pool.query('SELECT copies FROM books WHERE book_id = $id', [id]);
console.log("b");
const stock = copies - 1;
console.log("c")
const updateBook = await pool.query("UPDATE books SET copies = $1 WHERE book_id = $2", [stock, id]);
console.log("d")
const allBooks = await pool.query("SELECT * FROM books");
console.log("heee")
res.json(allBooks.rows);
} catch (err) {
console.error(err.message);
}
});
//return a book
app.put("/booksreturn/:id", async (req, res) => {
try {
const { id } = req.params;
const { copies } = req.body;
const returnBook = await pool.query(
"UPDATE books SET copies = $copies WHERE book_id = $id",
[copies = parseFloat(copies) + 1, id]
);
res.json("Book was returned!");
} catch (err) {
console.error(err.message);
}
});
//list of books in users possession
app.listen(5000, () => {
console.log("Baba... server don start on top port 5000.")
});