Home > Back-end >  ReactJS - How to set useState variable to the return value of a function
ReactJS - How to set useState variable to the return value of a function

Time:11-10

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

CodePudding user response:

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 (
    ...
  )
}
  • Related