I have a data called person in JSON format getting from API:
const [person, setPerson] = useState("");
const url = "http://localhost:8080/api/persons";
useEffect(() => {
axios.get(url).then((response) => {
setPerson(response.data);
});
}, [url]);
I'm trying to show that data in popup windows after clicking a button. The data is correct after checking using console.log
, but it always shows a blank white screen after I click a button.
return (
<div>
{person.map((item) => (
<tr>
<td>{item.name}</td>
</tr>
))}
</div>
However, if I tried to declare a dynamic data object
:
const person = [
{
"name": "John"
"age" : 35,
},
{
"name": "Jack"
"age" : 25,
}
]
return (
<div>
{person.map((item) => (
<tr>
<td>{item.name}</td>
</tr>
))}
</div>
then it works well. Anyone ever got this issue know how to fix?
CodePudding user response:
You initialize the person
variable with const [person, setPerson] = useState("");
which means that on first render person
will be a string and strings do not have a .map
method.
Use const [person, setPerson] = useState([]);
and you should be fine.
Since you expect it to be an array after the JSON is fetched, you should also initialize it to one.