Usually, it works, but right now it shows an error.
componentDidMount code
componentDidMount() {
axios.get(`${process.env.REACT_APP_DEV_URL}/admins/playlist_admin`, {
headers: {
'Authorization': this.state.token
}
})
.then((res) => {
this.setState({ list: res.data.response });
})
}
Render code
<MynTable headData={headData} className="bg-blue text-white myn-table" >
{
list ? //i checked in console. list has some data
list.map((playlist, index) =>
(
<tr key={index}>
<td>{playlist.id}</td>
<td>{playlist.name}</td>
<td>{playlist.songs.length}</td>
</tr>
))
: null
}
</MynTable>
Data is coming from APIs and got saved in the state still map function show error of map is not a function. if a changed the express list ? with list.length > 0 ? then error is removed but again render didn't return anything.
CodePudding user response:
You are using an array called list
which exists in your store
object but in the JSX segment, you didn't check the existence properly.
Wrong implementation:
if(list) {
return list.map()
} else {
return null
}
// or with ternary operator:
list ? list.map() : null
Explanation:
As you see above, the if condition will check the list
property which is a present property on the state
(since the list
property exists before the API call). So, checking the list
with the above methods always will return true
. to solve the issue, instead of checking the list
before mapping, try to check the length of it.
The Solution:
{
list.length > 0 ? list.map() : null
}
Note: you can use a short circuit for the above statement since the one side is null:
{
list.length > 0 && list.map()
}
CodePudding user response:
I fixed this problem with a loading indicator.
componentDidMount()
is going to call after render - that's why you are getting this error.
You have to make a loading state set to true with a condition in render if loading is false going to map data.
Set loading to false in componentDidMount()
after getting data to make sure that state is filled with data after that going to map it.