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

181
Vistas
ReactJS - Cómo establecer la variable useState en el valor de retorno de una función

Entonces, lo que tengo es una función, fillSidebarData(), que recopila y estructura datos para mí y, cuando termina, simplemente los devuelve. Lo que quiero hacer es establecer la variable "sidebarData" en el valor de retorno de esta función. Como referencia, los datos se ven así, si eso importa:

 SidebarData = [ { title: 'Overview', path: '/overview', subNav: [ { title: 'Users', path: '/users', }, { title: 'Revenue', path: '/revenue', } ] }

Aquí está el código para las funciones que crean los datos.

 const [sidebarData, setSidebarData] = useState([]) function fillSidebarData () { let sidebarData = [] UserService.getPosts(0).then((response) => { response.data.map((value, key) => { UserService.getPosts(value.PostID).then((response) => { let subNav = [] response.data.map((value, key) => { subNav.push({ title : value.postName, path: `/${value.PostID}` }) }) let sidebarItem = { title: value.postName, path: `/${value.PostID}`, subNav : subNav } sidebarData.push(sidebarItem) }) }) //The console log shows the data in the exact format I want it, so nothing weird here console.log(sidebarData) return sidebarData }, error => { console.log(error) }) } useEffect(() => { //Here is where I want to set the sidebar data to the return value of fillSideBarData method but sidebarData is undefined when using it elsewhere in the code. setSidebarData(fillSidebarData()) return () => { setSidebarData([]) } }, [sidebarData])
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Debido a que su pregunta carece de contexto, responderé su pregunta basándome en mi suposición de que está tratando de obtener los datos de navegación de su backend y renderizar su componente de navegación en función de los datos que obtuvo.

Estoy notando aquí que useEffect hook no se usa dentro del componente de función. De acuerdo con la documentación de React , usa Effect Hook para realizar efectos secundarios en el componente de función.

Para responder a su pregunta original, su setSidebarData debe llamarse dentro de la función fillSidebarData .

 const Nav = () => { const [sidebarData, setSidebarData] = useState([]) const fillSidebarData = () => { let sidebarData = [] UserService.getPosts(0).then((response) => { response.data.map((value, key) => { UserService.getPosts(value.PostID).then((response) => { let subNav = [] response.data.map((value, key) => { subNav.push({ title : value.postName, path: `/${value.PostID}` }) }) let sidebarItem = { title: value.postName, path: `/${value.PostID}`, subNav: subNav } sidebarData.push(sidebarItem) }) }) // Your setSidebarData needs to be called here setSidebarData(sidebarData) }) .catch(error => { console.log(error) }) } useEffect(() => { // If you are updating your menu data just once, // you probably do not need to resubscribe to your sidebarData state. fillSidebarData() }) return ( ... ) }
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