Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
  })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading