Two States
Button click and data appears
<button onClick={handleData}>get transactions details</button>
const handleData = async () => {
try {
const { status, data } = await fakeFetch3(
"https://example.com/api/transactions"
);
if (status === 200) {
console.log({ data: data.transactions });
setData(data.transactions);
}
} catch (e) {
console.log(e);
}
};
Another button to style the data based on conditons
const [highlight, setHighlight] = useState(false);
<button onClick={handleHighlight}>
highlight transaction greater than 1000
</button>
const handleHighlight = () => {
setHighlight(true);
};
<li
key={id}
style={{
listStyle: "none",
border: brderfun(amount),
padding: "1px",
}}
const brderfun = (amount) => {
if (highlight && amount > 1000) {
return " 3px solid red";
} else {
return " "; }}
UseEffect will run after the first render
Before render ---console.log
Useffect
If the state changes(render happens again when the usestate changes)
Before render
Useffect does not again render-it will render only once
useEffect(() => {
getProductsData();
}, []);
const [data, setData] = useState([]);
const getProductsData = async () => {
try {
const response = await fakeFetch1("https://example.com/api/wishlist");
if (response.status === 200) {
console.log({ data: response.data.wishlist });
setData(response.data.wishlist);
}
} catch (e) {
console.error(e);
}
};
How to do add text before useeffect fetch the data
const [loading, setLoading] = useState(false);
const getProductsData = async () => {
setLoading(true);
try {
const response = await fakeFetch1("https://example.com/api/wishlist");
if (response.status === 200) {
console.log({ data: response.data.wishlist });
setData(response.data.wishlist);
setLoading(false);
}
} catch (e) {
console.error(e);
}
};
useEffect(() => {
getProductsData();
}, []);
<p>{loading && "loading"}</p>
* Step I: No data in the first render
* Step IA: Create a state variable, initial value isLoading = false
* Step II: After the first render happen, async await got triggered
* data will come back
* Step II A: isLoading to false
* -- > state of the data is changed
* Step III: Then again, render will happen and we'll be able to
see the data