Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
Need help printing out a list from db

Been trying to print out a simple list from db for 2 days now, here's the code right now:

function CategoriesTable() {

const [isLoading, setLoading] = useState(true);
let item_list = [];
let print_list;

useEffect(() =>{
    Axios.get('http://localhost:3000/categories').then((response) => {

        const category_list = response.data.result;
        
        if(category_list) {
            for(let i = 0; i < category_list.length; i++){
                item_list.push(category_list[i].category_name)
            }
        }

        print_list = function() {
            console.log(item_list.map((item) => <li>item</li>))
            return item_list.map((item) => <li>item</li>)
        }

        setLoading(false);
    })      
}, [])


return (
    <div>
        { !isLoading && print_list }
    </div>
    )
}

I think the function should be executed after the loading state gets changed to false, right? For some reason the function is not executing

By the way, I can print out the list in console without a problem, rendering the list is the problem.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Basically rewrite from the ground up since the original code is quite messy I'm afraid.

Feel free to ask in the comments if you have any questions.

import { useState, useEffect } from "react";

import Axios from "axios";

/**
 * Why mix cases here? Are you gonna use camel or snake case? Choose one and only one.
 */
function CategoriesTable() {
  const [categoryNames, setCategoryNames] = useState([]);

  useEffect(() => {

    // not a good idea to use full URL on localhost
    Axios.get('/categories').then((response) => {
      const categoryList = response.data.result;

      if (categoryList) {
        const categoryNames = categoryList.map(({ category_name }) => category_name);
        console.log(categoryNames); // in case you want ot keep the console output
        setCategoryNames(categoryNames);
      }
    });
  }, []);


  return (
    <div>
      {/* You should either wrap <li> with either <ol> or <ul> */}
      <ol>
        {categoryNames.map(categoryName => (
          // key is required and should be unique in map statement. In here I assume there are no duplicated categoryName
          <li key={categoryName}>{categoryNames}</li>
        ))}
      </ol>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I would suggest to do something like this:

function CategoriesTable() {
    
  const [fetchedData, setFetchedData] = useState({
    result: [],
    isLoading: true,
  });
  
  useEffect(() =>{
      Axios.get('http://localhost:3000/categories').then(response => {
  
          const category_list = response.data.result;
          
          setFetchedData({
            isLoading: false,
            result: category_list.map(category => <li>{ category.category_name }</li>),
          })
      })      
  }, [])
  
  
  return (
      <div>
          { !fetchedData.isLoading && fetchedData.result }
      </div>
  )
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda