Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!