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 do i fetch data from the backend to the frontend?

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.

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 :

It should be:

useEffect(()=> {
    getTodos();
}, []);

Instead of:

useEffect = (()=> {
    getTodos();
}, []);

You declared a new variable by accident

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