F
F
FairyTaleComposer2022-01-15 04:55:46
React
FairyTaleComposer, 2022-01-15 04:55:46

Why is the result of a fetch request inside useEffect not written to state via useState?

import { useState, useEffect } from 'react';
import './App.css';
//import Loader from './components/Loader/Loader';
//import Error from './components/Error/Error';
import Form from './components/Form/Form';
import Table from './components/Table/Table';


export default function App() {
  const [tableData, setTableData] = useState(null);

  useEffect(() => {
    async function getTableData() {
      try {
        await fetch('http://localhost:5000')
          .then((res) => { return res.json() })
          .then((data) => { 
             //console.log(data)
            setTableData(data) 
          })
      }
      catch (err) {
        console.error(err);
      }
    }
    getTableData();
  }, []);

  return (
    <div className="wrapper">
        <Form />
        { tableData && <Table data={tableData} /> }
    </div>
  );
}


Here data correctly comes from the server and after res.json() it is displayed in the console, but does not want to be written to tableData. Why? And how to write it there? In this case, I'm trying to do an initial data load. But then I will need to update them after the user's actions (if he changes the filters), so it is necessary to write in the state in any case ...

I found a mistake and fixed it! For those who are experiencing this:
In the TableData component, I accepted data without curly braces. I added them and it worked. In fact, before that there were problems in the request itself, and the server's response was not recorded in tableData. This is already when I formulated the question, rewrote the code again, removing all unnecessary and some of the problems, apparently, too)) Then only the error with brackets remained. Just as a result, I received the same error in the console from the TableData component "data.map is not a function", that is, for some reason, the component with the table received not an array, but something else.

Although I still don’t understand where the wrapper in the form of an object came from when I send an array from the server.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2022-01-15
@FairyTaleComposer

Everything works, look for the error elsewhere:

V
Vladimir, 2022-01-15
@Casufi

Why async and await? Remove them from the code, they are useless here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question