Reputation: 35
I have a problem with returning data for an empty JSON. If there is data for a given user, everything works fine, unfortunately with empty JSON []
the data disappears and the else
condition does not work. Does anyone know how to fix this?
const Header = (): ReactElement => {
const url = '/api/header';
const [ data, setData ] = useState([]);
useEffect(() => {
axios.get(url).then((json) => setData(json.data));
}, []);
return (
<Container maxWidth="xs" justify-content="center">
{data.map((collection) => {
if (data.length > 0) {
return (
<Header>
data1: {collection['data1']}
<br />
data2: {collection['data2']}
<br />
data3: {collection['data3']}
<br />
</Header>
);
} else
return (
<Header>
{' '}
data4: 0 <br /> data5: 0
</Header>
);
})}
</Container>
);
};
I'd like to return this:
return (
<StatisticsHeader>
{' '}
data4: 0 <br /> data5: 0
</Header>
);
in case of an empty JSON
Upvotes: 1
Views: 257
Reputation: 2485
Here is the solution:
return (
<Container maxWidth="xs" justify-content="center">
{data.length > 0 ? (
data.map((collection) => (
<Header>
data1: {collection.data1}
<br />
data2: {collection.data2}
<br />
data3: {collection.data3}
<br />
</Header>
))
) : (
<Header>
{' '}
data4: 0 <br /> data5: 0
</Header>
)}
</Container>
);
Upvotes: 1
Reputation: 3244
You're checking data.length
inside data.map
method. Since data is empty, data.map
never renders anything, along with your condition.
Proper code would look like this:
const Header = (): ReactElement => {
const url = '/api/header';
const [data, setData] = useState([]);
useEffect(() => {
axios.get(url).then((json) => setData(json.data));
}, []);
return (
<Container maxWidth="xs" justify-content="center">
{data.length > 0 ? (
data.map((collection) => (
<Header>
data1: {collection.data1}
<br />
data2: {collection.data2}
<br />
data3: {collection.data3}
<br />
</Header>
))
) : (
<Header>
{' '}
data4: 0 <br /> data5: 0
</Header>
)}
</Container>
);
};
data.length > 0 ? ... : ...
is a shorthand way of doing if (data.length > 0) { ... } else { ... }
called the ternary operator.
Some other useful tips:
const url = 'api/header';
outside your component, like this: const url = '/api/header';
const Header = (): ReactElement => {
...
That way the URL constant won't re-render unnecessarily since it is static.
React.FC
:Instead of:
const Header = (): ReactElement =>
Use:
const Header: React.FC = () =>
Upvotes: 2