So, I am getting the below error,
inspected via google chrome
What I am trying to achieve is to explore the Fetch Api by retrieving some data via userApi.js file which pulls it from a srcServer.js (I have hardcoded some data here). I am using webpack bundle and index is the entry point of my project. I have created index.html to bind the data via innerhtml.
Earlier I was using import 'isomorphic-fetch'
in my userApi.js file but that too didn't help and hence I found some suggestions on google to use isomorphic-fetch, node-fetch etc. nothing of that sort worked.
I have added most of the artifacts below can you please guide me what is that I am missing here.
Project Structure
userApi.js
import 'isomorphic-fetch'
import 'es6-promise'
export function getUsers () {
return get('users')
}
function get (url) {
return fetch(url).then(onSuccess, onError) //eslint-disable-line
}
function onSuccess (response) {
return response.json()
}
function onError (error) {
console.log(error)
}
index.js
/* eslint-disable */ // --> OFF
import './index.css'
import {getUsers} from './api/userApi'
// Populate table of users via API call.
getUsers().then(result => {
let usersBody = ''
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${user.id}' class='deleteUser'>Delete</a></td>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
</tr>` //eslint-disable-line
})
global.document.getElementById('users').innerHTML = usersBody
})
index.html
<!DOCTYPE <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Users</h1>
<table>
<thead>
<th> </th>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody id="users">
</tbody>
</table>
<script src="bundle.js"></script>
</body>
</html>
srcServer.js
// sample api call data
app.get('/users', function (req, res) {
// Hard coded for simplicity
res.json([
{ 'id': 1, 'firstName': 'P', 'lastName': 'K' },
{ 'id': 2, 'firstName': 'M', 'lastName': 'K' },
{ 'id': 3, 'firstName': 'S', 'lastName': 'K' }
])
})
The error is giving you the exact reason, i.e. user
is not defined. Have you tried to print console.log(element);
in your forEach loop? You will see what you need to change.
You are accessing the user information incorrectly. In your forEach loop, each value is represented as element
not user
result.forEach(element => {
usersBody+= `<tr>
<td><a href='#' data-id='${element.id}' class='deleteUser'>Delete</a></td>
<td>${element.id}</td>
<td>${element.firstName}</td>
<td>${element.lastName}</td>
</tr>` //eslint-disable-line
})