React is not rendering my mapped array after using asyn functions to call on API
I use the following useEffect to get characters into an array and set it as state in setRelatedCharacters
// Find related characters
useEffect(() => {
// for promise to work in useEffect. need to put async function inside then call it
const relatedCharacters = async () => {
// if data exist. set related characters array by calling utility function and wait for it
if (data) setRelatedCharacters(await relatedSwapi(data.characters));
};
relatedCharacters();
}, [data]);
Then, when logging relatedCharacters, I get an array of 17 objects(characters).
Next, I send a condition to wait until the array is full of characters and when full I try to map through the array and render a name for each object in array. However, it quickly flickers and then disappears. I have no idea why.
{!data && !relatedCharacters ? (
<Loading />
) : (
<div>
<p>hello</p> // renders
{console.log(relatedCharacters, "<= relatedCharacters")} // shows correct array
{relatedCharacters?.map((character) => (
<p key={character.name}>{character.name}</p> //DOESN'T SHOW, SLIGHTLY FLICKERS ONLY
))}
</div>
)
-- EDIT FOR COMMENT -- Here is the entire code once taking away everything else
const Film = () => {
const location = useLocation();
const url = location.state.url;
const index = location.state.index;
const [data, setData] = useState(null);
const [relatedCharacters, setRelatedCharacters] = useState(null);
// Find related characters
// PROBLEM HAS TO BE HERE I THINK AS PROMISES AND SUCH ARE ACTING UP
const relatedSwapi = (data) => {
let relatedArray = [];
data.map(async (url) => {
const related = await callSingleSwapi(url);
relatedArray.push(related);
});
return relatedArray;
};
useEffect(() => {
const fetchCharacters = async () => {
// if data exist. set related characters array by calling utility function and wait for it
if (data) {
const x = await relatedSwapi(data.characters);
setRelatedCharacters(x);
}
};
fetchCharacters();
}, [data]);
return (
<div>
<div className="relatedWrapper">
<div className="flex space-x-3">
{console.log(relatedCharacters, "<= related Characters")} // RENDERS AND THEN GOES BACK TO NULL
{relatedCharacters?.map((character) => (
<p key={character.name}>{character.name}</p>
))}
</div>
</div>
)}
</div>
);
};
export default Film;