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

333
Vistas
Error on fetch data, function instead of value

Hi guys I am trying to fetch data using get, and I want the data to be displayed after I click on the button, as a normal crud I am new in programming if there is someone that can help me. I APPRECIATE THANKS everything in my backend is ok, I try in postman and console.log is everything good. My problem is only in this part thanks


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



 function Usuarios() {
    const [users, setUsers] = useState([]);

     useEffect(()=> {
        const todosUsers = async () => {
            const res= await axios.get("/users");
            console.log(res)
            setUsers(res.data);
        }
        todosUsers()
    },[])
 
    return (
        <>
        <button onClick=
        {users.map((users) => ( 
            <h1>{users.username}</h1>
            ))}></button>
        </>

        )
}

export default Usuarios;

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

0

one solution would be to keep a seperate variable to see if button is clicked as S.Singh mentioned

  const [users, setUsers] = useState([]);
  const [clicked, setClicked] = useState(false);

and in your component you can set the clicked variable to true on click

 return (
        <>
        <button onClick={() => setClicked(true)}></button> //setting clicked true onclick
        {clicked && users.map((users) => (  //only renders when click is true
            <h1>{users.username}</h1>
         ))}
        </>

        )

if you want to hide and show alternatively on click just change the line to onClick={() => setClicked(!clicked)}

codesandbox demo

about 4 years ago · Juan Pablo Isaza Denunciar

0

Move

 {users.map((users) => ( 
        <h1>{users.username}</h1>
        ))
 }

from onClick definition and place it in an a markup where you want it to render. Define onClick hendler, which will be setting data from an API to a state

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

  function Usuarios() {
      const [users, setUsers] = useState([]);

      const fetchOnClick = async () => {
          await axios.get("/users");
          console.log(res)
          setUsers(res.data);
      }

      return (
          <>
              <button onClick={fetchOnClick}>
                  Fetch
              </button>
              <div>
                  {users.map((users) => ( 
                      <h1>{users.username}</h1>
                  ))}
              </div>
         </>

    )
 }

OR

If you want to fetch the data inside useEffect hook, like you did in your example

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

     function Usuarios() {
         const [users, setUsers] = useState([]);
         const [isContainerShowed, setIsContainerShowed] = useState(false)

         useEffect(() => {
             const res= await axios.get("/users");
             console.log(res)
             setUsers(res.data);
         }, [])

         const displayContainer = () => setIsContainerShowed(true);

         return (
             <>
                 <button onClick={displayContainer}>
                     Fetch
                 </button>
                 <div style={{display: isContainerShowed ? "block" : "none"}}>
                     {users.map(users => <h1>{users.username}</h1>)}
                 </div>
             </>

        )
     }
about 4 years ago · Juan Pablo Isaza Denunciar

0

use Effect hook runs every time the component is rendered but as I understand, you want to display users when the button is clicked, so you can fetch users once the button is clicked and display them using the code below

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

 function Usuarios() {
    const [users, setUsers] = useState([]);

    
    const fetchUsers= async () => {
            const res= await axios.get("/users");
            setUsers(res.data);
    }
 
    return (
        <>
          <button onClick={() => fetchUsers()}></button>
          {
             users.length && users.map(user => <h2>{user.username}</h2>) 
          }
        </>

        )
}

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