Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda