I am using a component called <Player/>
, which either displays a page with "player not found" or loads the data of a queried and saved player.
The component has a local state, which is player
, and by default is null. There is a useEffect
that fetches to the database with the username as a parameter, and if a user is found the JSON returned is saved and set to the state with setPlayer(res)
. If no user is found from the fetch, then the state remains to null
.
When the state is null
the page renders 'user not found'. When the state is not null (meaning it found a player), I load the info.
This is working as planned, however when going to a route like player/existingPlayer
, the page renders for a quick second not found
before then updating and displaying the players data correctly.
Is this the only way possible to do this? Is this to be expected? I know data fetching inherently takes a few seconds depending on the connection, but I feel this severly user experience.
Any suggestions to improve this?
CodePudding user response:
When player is null show loading, and after fetching player info if it does exist just show player info if not set empty ""
and if your state was equals to ""
show not found player like so
export default function App() {
const [player, setPlayer] = useState(null)
useEffect(() => {
// fetch here and set player to "" if not found
}, [])
if(player == null) return <div>Loading...</div>
if(player == "") return <div>No Player Found.</div>
return (
<div className="App">
Player info goes here...
</div>
);
}