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

183
Vistas
ReactJS - How to set useState variable to the return value of a function

So what I have is a function, fillSidebarData(), that gathers and structures data for me and when done just returns it. What I want to do is set the variable "sidebarData" to the return value of this function. For reference the data looks like this, if that matters:

SidebarData = [
  {
    title: 'Overview',
    path: '/overview',

    subNav: [
      {
        title: 'Users',
        path: '/users',
      },
      {
        title: 'Revenue',
        path: '/revenue',
      }
    ]
  }

Here is the code for the functions that creates the data.

  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

Because your question is lacking some context, I will answer your question based on my assumption that you are trying to fetch the nav data from your backend and render your nav component based on the data you fetched.

I am noticing here that useEffect hook is not used within the function component. According to React documentation, you use Effect Hook to perform side effects in function component.

To answer your original question, your setSidebarData needs to be called within fillSidebarData function.

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