Home > Blockchain >  How do i fetch data from the backend to the frontend?
How do i fetch data from the backend to the frontend?

Time:08-08

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 >
<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.

CodePudding user response:

It should be:

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

Instead of:

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

You declared a new variable by accident

CodePudding user response:

I think your code is good but the problem is with something else, please show the output in your console.

Also, try replacing the 'http://localhost...' to 'https://jsonplaceholder.typicode.com/users' and see if the fetch works.

CodePudding user response:

Try this and tell me what's in the console

useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
  .then(data => data.json())
  .then(setTodos)
  .catch(console.error);
});

  • Related