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

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

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