0% found this document useful (0 votes)
3 views3 pages

Useeffect Notes

Uploaded by

ahmed.high212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Useeffect Notes

Uploaded by

ahmed.high212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

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

You might also like