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

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

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 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