I have this get API in my server side (Node JS):
app.get("/todos", async(req, res)=>{
try {
const allTodos = await pool.query("select * from todo;");
res.json(allTodos.rows);
} catch (err) {
console.error(err.message);
}
})
And of course it works when i tried it with Postman!
And here i have my ListTodo.js in my client side (React JS) in which i try to fetch data in it and display it in a table:
import React, { Fragment, useState, useEffect } from "react";
const ListTodo = () =>{
const [todos, setTodos] = useState([]);
const getTodos = async() => {
try {
const response = await fetch("http://localhost:5000/todos")
const jsonData = await response.json();
setTodos(jsonData)
} catch (err) {
console.error(err.message);
}
}
useEffect = (()=> {
getTodos();
}, []);
console.log(todos);
return (
<Fragment>
<table class="table">
<thead>
<tr>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{todos.map(todo => (
<tr>
<td>{todo.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
))}
</tbody>
</table>
</Fragment>
);
}
export default ListTodo;
So if i try to console.log(jsonData) i get 2 empty arrays.
>Solution :
It should be:
useEffect(()=> {
getTodos();
}, []);
Instead of:
useEffect = (()=> {
getTodos();
}, []);
You declared a new variable by accident