I have problems with useState and useEffect. Here is the code:
const [words, setWords] = useState()
useEffect(() => {
getAllData()
}, [])
async function getAllData(category){
let url = `http://127.0.0.1:3000/api/improve-language`
let response = await fetch(url)
let data = await response.json()
let result = await data
await setWords(result)
}
I expect from useEffect to get data from api and set to useState variable. And then I'm going to use that useState variable anyway. But, when the website load, I see that useState variable is null, after when I writing a new code line and saving the file, then I see that useState variable has the data finally.
I need to get the data before the website rendering procces. I need to have the data when the page loads. Otherwise, I'm getting errors.
Update: Thanks to everyone who answered to question. Everyone says "use a loader" but I'm already using it. But the main problem is not this.
There are lots of functions and useState variables. And I need the data immediately to make other functions and useState variables to useable.
I'm aldreay using loading effect, but the main problem is functions needs words variable which works for make datas to useable and to present to user.
I need that data after using the setWords(data) function which is in getAllData() function.
I need datas before everything.
Rather then creating a async function inside the functional hook, you can create a function inside useEffect which gets called on component mount and display a loading spinner when data is being fetched. This is my approach for the above problem statement
const LoadingDiv = styled.div`
display: flex;
justify-content: center;
align-items: center;
`
const [words, setWords] = useState()
useEffect(() => {
const getAllData = async() => {
let url = `http://127.0.0.1:3000/api/improve-language`;
let response = await fetch(url)
let data = await response.json()
setWords(data)
};
getAllData();
}, [])
return (
words ?
<YourComponents.../> : <LoadingDiv > Loading... < /LoadingDiv>
);
First, you are using more await than it is needed. That has been said, you can use some loading component while you are fetching the data (it is the recommended way), like so :
const [words, setWords] = useState()
useEffect(() => {
getAllData()
}, [])
async function getAllData(category){
let url = `http://127.0.0.1:3000/api/improve-language`
let response = await fetch(url)
let data = await response.json()
setWords(data)
}
if(!words){
return <p>Loadin ...</p>
}
I think the easiest way is that you would display a loading spinner until you have data in words. That way, the page will load, your spinner will show until theres data, then when data is in you can remove the spinner and actually display your content