Search code examples
reactjsrenderingrender

Why is this not rendering from a map, in react


So I get items from a DB and console.log them just before, so I know they exist and are in the format I want them to be. I also wrote a simple method to make sure rendering works. The code looks something like this (is simplified for nonrelevantbits)

const renderSomething = () => {
getFromDB().then(function(data){
if (data) {
            console.log(data.something)  //returns an array in console          
          return data.something.map(somet => { 
                console.log(' somet is ' + somet) //return somet with quotes: ""              
                return <p>{somet}</p>
            })
        } else {
            console.log("No data!");
        }
}
}

and then in the return:

   return (
<div>
{renderSomething()}
</div>
)

And nothing appears on the screen. I made a test one to make sure it should:

const basic = () => {
    return ['abc', 'bca'].map(num =>  <h1>{num}</h1>)
}

 return (
        <div>
           {basic()}
        </div>
    )

The test one worked


Solution

  • Render function cannot be a promise. You should useEffect method to downlaod the data from api and then useState to set it for the component.

    import React, { Fragment, useState, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    function LiveVisitors() {
      const [visitors, setVisitors] = useState([
        {
          ip: "",
          countryCode: "",
          city: "Warsaw",
          state: "",
          country: "Poland"
        },
        {
          ip: "",
          countryCode: "",
          city: "Gdańsk",
          state: "",
          country: "Poland"
        }
      ]);
      const { ip, countryCode, city, state, country } = visitors;
    
      useEffect(() => {
        getUserData();
      }, []);
    
      const getUserData = () => {
        //imitate fetch
        setVisitors([
          ...visitors,
          {
        ip: "",
        countryCode: "",
        city: "Wrocław",
        state: "",
        country: "Poland"
          }
        ]);
      };
    
      return (
        <div>
          {visitors.map((el) => (
        <div>{el.city}</div>
          ))}
        </div>
      );
    }
    
    const wrapper = document.getElementById("container");
    ReactDOM.render(<LiveVisitors />, wrapper);
    

    Here is the interactive version where you can play with it. https://codesandbox.io/s/react-playground-forked-hqswi?file=/index.js:0-947