Im learning JS and React and I came to the code example below and some parts I don’t understand properly. The second .then is inside useUffect is this ok, or it’s better to be in getData func? Also in render there is data**?**.map and I don’t understand why we need ?, is this ternary operator? Is so I thought that ternary operator requires : as a second parameter. Thanks in advance!
JavaScript
x
24
24
1
import React, { useState, useEffect } from "react";
2
3
const FetchData = () => {
4
const [data, setData] = useState(null);
5
const fetchURL = "https://jsonplaceholder.typicode.com";
6
7
const getData = () => fetch(`${fetchURL}/posts`)
8
.then((res) => res.json());
9
10
useEffect(() => {
11
getData().then((data) => setData(data));
12
}, []);
13
14
return (<div>
15
{data?.map(item => (
16
<ul>
17
<li>{item.title}</li>
18
</ul>
19
))}
20
</div>);
21
};
22
23
export default FetchData;
24
Advertisement
Answer
I think, your code is fine, Move getData and fetchURL
into useEffect
incase if there’s any error.
Also, You can simply use async/await
approach for the same.
JavaScript
1
26
26
1
import React, { useState, useEffect } from "react";
2
3
const FetchData = () => {
4
const [data, setData] = useState(null) // here you can define `[]` if you don't want to check `?`
5
useEffect(() => {
6
const fetchURL = "https://jsonplaceholder.typicode.com";
7
const getData = async () => {
8
const res = await fetch(`${fetchURL}/posts`)
9
const result = await res.json();
10
setData(result);
11
}
12
getData()
13
14
}, []);
15
16
return (<div>
17
{data?.map(item => (
18
<ul>
19
<li>{item.title}</li>
20
</ul>
21
))}
22
</div>);
23
};
24
25
export default FetchData;
26
?
is Called Optional Chain Operator, which will help you to check whether the value is nullish (null or undefined)
.
Basically, it just doing if (data) { data.map...}