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

205
Visualizações
i'm trying to make a axiosGET request to my react component, i get the object on the console.log. But when i try to render it i get a "is not defined"
//component 
const Clientslist = () => {
  const classes = useStyles()

  axios.get('/api/clients').then(resp => {
    const {clients} = resp.data
    console.log(clients) // i get the data on the terminal
    
  })

    return(
        ...
       {
          clients.map(client => ( //clients is not defined
              <Grid key={client._id} item xs={12} sm={6} md={4}>
                  <Card 
                    clientName={client.clientName}
                    ...
          )
       }

//controller 
   const get = async (req, res) => {
     await dbConnect()
     const clients = await ClientsModel.find()
     res.status(200).json({ success: true, clients})
   }

I thing my request code is poor, if someone helps me fix the problem and even a code refactor for a better and clean code. It would be great. Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

your clients variable is defined inside the scope inside the axios callback, and can't be accessed from outside, but if you modified it alittle bit, you can save it inside a local state variable, like: (3 new lines are marked with //***)


//component 
const Clientslist = () => {
  const classes = useStyles()
  //*** Adding clients var with initial value as empty array 
  const [clients, setClients] = useState([]) //***

  axios.get('/api/clients').then(resp => {
    const {clients} = resp.data
    console.log(clients) // i get the data on the terminal

    setClients(clients) //*** this would save the new clients in the sate
  })
about 4 years ago · Juan Pablo Isaza Relatório

0

In your code, clients variable is in the local scope of axios thus not accessible in the return statement. As you are using React functional Component, we can use useState hook which helps us to track the state of the variable

//component 
import React, { useState } from 'react';
const Clientslist = () => {
const classes = useStyles();
const [clients, setClients] = useState([]);// empty array denotes initial state

axios.get('/api/clients').then(resp => {
  const {clients} = resp.data
  console.log(clients)
  setClients(clients); // sets the state of variable clients to the received data
})

return(
    ...
  {
    clients.map(client => (// updated clients can be used here to display .Also check for the valid response before mapping
       <Grid key={client._id} item xs={12} sm={6} md={4}>
         <Card 
           clientName={client.clientName}
                ...
      )
   }

Helpful resources : https://reactjs.org/docs/hooks-state.html https://www.geeksforgeeks.org/what-is-usestate-in-react/

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