When I refreshed the page my app crashes. This was due to my page loading in faster than my data. I think… SO I added additional checks using the logical AND (&&) operator. Is this best practice? It just seems odd to have to do this everywhere. Is there a better, more practical way around this?
I was just messing around with how I fetch APIs. This isn’t from any special project of mine just a little sandbox file.
This is what the code looked like when it was crashing on page refresh…
import React, { useEffect, useState } from "react";
import { Heading } from "./components/Heading";
const URL = "https://api.sleeper.app/v1/league/867824542855376896";
function App() {
const [data, setData] = useState(null);
const getData = async () => {
try {
const res = await fetch(URL);
const data = await res.json();
setData(data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);
console.log(data);
return (
<>
<Heading str="Hello world" />
<Heading str="Hello friend" />
<h1>{data.bracket_id}</h1>
{data.roster_positions.map((pos, i) => {
return <h1 key={i + 1}>{pos}</h1>;
})}
</>
);
}
export default App;
And this is what I did to fix it…
import React, { useEffect, useState } from "react";
import { Heading } from "./components/Heading";
const URL = "https://api.sleeper.app/v1/league/867824542855376896";
function App() {
const [data, setData] = useState(null);
const getData = async () => {
try {
const res = await fetch(URL);
const data = await res.json();
setData(data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
getData();
}, []);
console.log(data);
return (
<>
<Heading str="Hello world" />
<Heading str="Hello friend" />
<h1>{data && data.bracket_id}</h1>
{data &&
data.roster_positions.map((pos, i) => {
return <h1 key={i + 1}>{pos}</h1>;
})}
</>
);
}
export default App;
Is there a better way of doing this beside add a logical AND operator before every use of my data?
2
Answers
Here I Have Made Some Update on Your Code On Mine Experience Which i have faced issue previously so i write code like this
I You Like This way Then You Can Follow It
A combination of conditionals and Array can be used.
This is what I came out with after an hour of trial and error
Based on How to concatenate two JSX fragment or variables or string and component (in Reactjs)?