I am learning react and have below observation .
I am not able to understand the reason behind the error.
I have below code -
React:
useEffect(()=>{
console.log()
axios.get('http://localhost:8000/api/records/').then((data) => {console.log('server returned ... ',typeof(data));setRecords(data)}
).catch( e => console.log(e))
},[])
const [records,setRecords] = useState([]);
When only
data
is used in sidethen clause in axios
, I get below error ,Uncaught TypeError: records.map is not a function
But when I change the code as below - please note
{data}
instead of justdata
, the above error is resolved.axios.get('http://localhost:8000/api/records/').then(({data}) => {...}
Can anybody please explain the above behaviour ?
I tried to print the type of variable data
, but in both cases it is coming as object
Why above error is gone when {data}
is used instead of {data}
Express:
const express = require('express')
const app = express()
var cors = require('cors')
const port = 8000
app.use(cors())
const Records = [
{
recordName:'First Record',
artistName:'First Artist',
description: 'First Artist Description'
},
{
recordName:'Second Record',
artistName:'Second Artist',
description: 'Second Artist Description'
}
]
app.get('/api/records', (req, res) => {
res.send(Records)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
CodePudding user response:
Try to set your data as below because in axios we get response in object
const [records,setRecords] = useState([]);
useEffect(()=>{
console.log()
axios.get('http://localhost:8000/api/records/').then((resData) => {console.log('server returned ... ',typeof(resData));setRecords(resData.data || [])}
).catch( e => console.log(e))
},[])