I am having trouble with my fetch function and the usage. I am able to get my data from the data state but its returning a full string instead of an array that I can map. I have been playing around with it for a few hours and cant get my head wrapped around it.
import react, { useState, useEffect } from "react";
import { Carousel } from "@mantine/carousel";
var PATH = "/Quests/questlist.txt";
function App() {
const [data, setData] = useState<any>(null);
let newData = [""];
useEffect(() => {
getText();
}, []);
async function getText() {
fetch(`${PATH}`)
.then((response) => response.text())
.then((text) => {
setData(text.split(","));
});
newData = data;
console.log(data);
}
return (
<div>
<Carousel
className="App"
maw={320}
mx="auto"
withIndicators
`your text`height={200}
>
{newData.map((sm) => {
return <Carousel.Slide>{sm}</Carousel.Slide>;
})}
</Carousel>
</div>
);
}
export default App;
To be able to map my array with the carousel components
some questlist.txt text {
Aftermath,
All Fired Up,
Alpha vs Omega,
Ancient Awakening,
Animal Magnetism,
Another Slice of H.A.M.,
As a First Resort,
Azzanadra’s Quest,
Back to my Roots,
Back to the Freezer,
Battle of the Monolith,
Beneath Cursed Tides,
Between a Rock…,
Big Chompy Bird Hunting
}
2
Answers
I really appreciate everyone's input I am happy to say I have figured it out. I do have other problems but I would rather solve them myself. This fetch function just wasnt sitting right with me because I knew it was correct I was just missing a type.
This was my final result. I appreciate you guys! First great interaction with the community!
There are two issues here:
From what I can see, you presume that the promise from the fetch call is not asynchronous. And the second issue is that useState is not set immediatly when calling
setData
.When you call fetch.then() it does not run immediatly. It continues execution in your example continues to the line
newData = data;
. And when it resolves the file it will execute the callback. So when you are setting the newData it is setting the initial value of data which isnull
.Also if it would for some reason immediatly execute the callback and setData and after that the
newData = data;
it would still not work as react does not immediatly set the state when calling setData. Only on the next render it has updated the state.It was already suggested to drop the
newData
variable which is a good idea to me. Here is an updated version of your getText function:Also using
async
for your function and not usingawait
does not really do anything.