0

I'm using react for the frontend, node and mongoDB compass for the backend, I send some information from the database to react, but I keep still getting it as a promise, I need it as an array, but I cannot get it.

Front-end and back-end

const consulta = async () =>{
    let dataRequest = {
      method: 'GET'
    }
    let url = new URL("http://localhost:5000/reservar");
    let response = await fetch(url, dataRequest);
    let result = await response.json();
    return result;
  }

  let promesa = consulta();
  let data_ = promesa.then(function(val) {
    console.log(val);
  });
  console.log(data_);




app.get('/reservar', function(req, res){
    // var userMap = {};
    var userMap = [];
    User.find({estado: 'No reservado'}, function(err, users) {
    
        users.forEach(function(user) {
           userMap.push(user);
          // userMap[user._id] = user;
        });
        res.json(userMap);  
      });
});```    

  • No, I'm using react, and also I obtain the response, but as a promise I cannot make it an array – andres florian Apr 26 '22 at 19:45
  • You're probably going to want to use `useEffect` and set your array after you do your async task – async await Apr 26 '22 at 19:46
  • `useEffect(() => { consulta().then(presumablyAnArray => setUsers(presumablyAnArray )) });` along with `const [users, setUsers] = useState()` probably. I'm assuming that your request (the backend part) works - doesn't appear to be anything out of place with that at a glance – Luke Briggs Apr 26 '22 at 19:50

1 Answers1

2

In react, if you have an async task like requesting info from a database, you probably want useEffect to change things either. Here is a small example of how it could be done in react.

import React, {useState, useEffect} from "react";

function App(props) {
  const [asyncData, setAsyncData] = useState("loading");
  useEffect(() => {
    (async () => {
      const dataRequest = {
        method: 'GET'
      }
      const url = new URL("http://localhost:5000/reservar");
      const response = await fetch(url, dataRequest);
      const result = await response.json();
      setAsyncData(result);
    })();
  }, []);
  return (
    <div>
      {JSON.stringify(asyncData)}
    </div>
  );
}
async await
  • 1,967
  • 1
  • 8
  • 19
  • Thanks. I tried but It tells me that Uncaught Error: Objects are not valid as a React child :( – andres florian Apr 26 '22 at 20:17
  • Sounds like you're getting the object back now. That's good progress. You can't display an object directly, you probably need to extract data from the object. try just logging it instead of returning jsx, and you can see what your data looks like – async await Apr 26 '22 at 20:25