I don't really have an error but I'm not getting the desired outcome. I have a Flask API as my backend. It returns JSON data, this data is then passed to the React frontend to be displayed after certain actions such as a button click.
The Flask backend is working fine, the data is being sent to the React frontend and I can use console.log(data)
to see it in the console.
The issue is I tried doing something to make it so that while the data is being fetched from the API, I want a message such as "Loading..." to be displayed.
Here's what I did in that regard.
const [data, setData] = useState([{}])
useEffect(() =>{
fetch("/details").then(
res => res.json()
).then(
data => {
setData(data)
console.log(data)
}
)
}, [])
That console.log(data)
does show my the JSON response in the console.
Then I do this for the display.
return (
<div>
...
<div>
{(typeof data.members === 'undefined') ? (
<p>Loading...</p>
) : (
data.members.map((member, i) => (
<p key={i}>{member}</p>
))
)}
</div>
</div>
);
This is supposed to display "Loading..." while the data is being fetched and then display the data. But it keeps displaying "Loading..." even though my data was fetched and it's never displayed.
I tried both answers as suggested and got this error on both attempts.
TypeError: Cannot read properties of undefined (reading 'map')
in line <p>Loading...</p>
CodePudding user response:
First of all, you set the initial value of the data
state to an array, but use it as an object. ( data.members )
If the data come from API is an object not an array, You need to set it as an object.
const [data, setData] = useState({})
Then you can check if the object has been set or not, you can check by the length of the object keys
return (
<div>
...
<div>
{Object.values(data).length ? (
<p>Loading...</p>
) : (
data.members.map((member, i) => (
<p key={i}>{member}</p>
))
)}
</div>
</div>
);
CodePudding user response:
I would edit the code like:
const [data, setData] = useState([])
(
<div>
...
<div>
{(data.length === 0) ? (
<p>Loading...</p>
) : (
data.members.map((member, i) => (
<p key={i}>{member}</p>
))
)}
</div>
</div>
);
Its likely, that members is still undefined after setting the state.