Two States
Button click and data appears
<button onClick={handleData}>get transactions details</button>
const handleData = async () => {
try {
const { status, data } = await fakeFetch3(
"[Link]
);
if (status === 200) {
[Link]({ data: [Link] });
setData([Link]);
}
} catch (e) {
[Link](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 ---[Link]
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("[Link]
if ([Link] === 200) {
[Link]({ data: [Link] });
setData([Link]);
}
} catch (e) {
[Link](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("[Link]
if ([Link] === 200) {
[Link]({ data: [Link] });
setData([Link]);
setLoading(false);
}
} catch (e) {
[Link](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