0

I've been trying to figure out why my code doesn't work for an hour now. So basically I want to fetch some data from a MySQL database, my serverside code is working as expected but whenever I try to fetch it in the client with the following code setting the state fails:

const [data, setData] = useState(null);

  useEffect(() => {
    const loadData = () => {
      fetch("http://localhost:5000/getusers")
        .then((response) => response.json())
        .then((data) => {
          setData(data); // data is undefined but when consoled-out it's in proper form
        });
    };
    loadData();
    console.log(data);
  }, [data]);

data is an array of objects. I assume I can't pass setState in a promise because I've added a conditional for rendering the data so even if it's null it just won't render but I receive a TypeError: data.map is not a function (it would be great if someone could explain how this happens).

CapBul
  • 55
  • 1
  • 9
  • Part of the answer is: [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron Jun 10 '21 at 19:42
  • Where is `data` undefined? It will be null in your log statement because the fetch hasn't happened yet. It sounds like your solution of not rendering until you have actual data is a good solution. – Bafsky Jun 10 '21 at 19:44
  • 1
    Also, [promises are asynchronous](https://stackoverflow.com/q/14220321/1218980), meaning that the console log happens before the actual fetch is completed. – Emile Bergeron Jun 10 '21 at 19:44
  • yes ! Thank you very much. – CapBul Jun 10 '21 at 19:45
  • 1
    The code is fine in a way, if you'd put the console log outside the `useEffect`, it would log `null` once, than it would log the right data on the next render. – Emile Bergeron Jun 10 '21 at 19:46
  • 1
    Also, you don't need to put the `fetch` inside a new function, just calling it inside the `useEffect` callback is fine. – Emile Bergeron Jun 10 '21 at 19:47
  • 1
    Thank you all for the advice, I refactored the useEffect code and now it's working properly. The 'data.map is not a function' error was because data was an object with a data key with the expected array as value ... I have no idea how I missed this. – CapBul Jun 10 '21 at 20:24

0 Answers0