I'm using react-redux and I have something like this in my code:
<div>
{episode.charactersList.map((id) => {
const character = characters.find(
(el) => String(el.id) === String(id)
);
return (
<div key={uuidv4()}>
{character ? (
<Link to={`/users/${character.id}`}>
{" "}
{character.name}{" "}
</Link>
) : (
<div key={id}> none</div>
)}
</div>
);
})}
</div>
The problem with this code is that when I delete one of the characters, I get <div> none </div> displayed. I don't know how to get rid of this since I have to use { character ? ( ...... ). If i skip this line of code the page is displayed before the data is being loaded and I get a error of undefined character.
To resolve the issue, you could test for a valid value of character before your return statement and abort the character from being rendered by returning null. For example:
<div>
{episode.charactersList.map((id) => {
const character = characters.find(
(el) => String(el.id) === String(id)
);
if (!character) {
return null;
}
return (
<div key={uuidv4()}>
<Link to={`/users/${character.id}`}>
{" "}
{character.name}{" "}
</Link>
</div>
);
})}
</div>