AJAX এবং APIs
আমি কিভাবে AJAX ব্যবহার করবো?
React এর সাথে আপনি যেকোনো AJAX লাইব্রেরি ব্যবহার করতে পারবেন। কয়েকটি বিখ্যাত AJAX লাইব্রেরি হলো Axios, jQuery AJAX এবং ব্রাউজারের নিজস্ব window.fetch।
আমি কম্পোনেন্টের জীবনচক্রের কোথায় AJAX ব্যবহার করবো?
আপনার উচিত componentDidMount
জীবনচক্রের মেথডে ডাটা লোড করা। কারণ, এভাবে আপনার ডাটা লোড হওয়ার পর আপনি setState
ব্যবহার করে আপনার কম্পোনেন্টের state পরিবর্তন করতে পারবেন।
উদাহরণ: AJAX এর তথ্য ব্যবহার করে স্থানীয় state সেট করা।
নিচের কম্পোনেন্টে componentDidMount
এ কিভাবে AJAX ব্যবহার করে স্থানীয় state পরিবর্তন করা যায়, তা দেখানো হয়েছে।
উদাহরণের API-টি নিচের মতো JSON object ফেরত পাঠায়ঃ
{
"items": [
{ "id": 1, "name": "Apples", "price": "$2" },
{ "id": 2, "name": "Peaches", "price": "$5" }
]
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// বিঃদ্রঃ এখানে catch() ব্লক এর বদলে error
// সামলানো খুবই গুরুত্বপূর্ণ কেননা আমরা চাই না
// কম্পোনেন্টের আসল কোনো সমস্যা হজম করতে।
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
Here is the equivalent with Hooks:
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
Is this page useful?এই পৃষ্ঠাটি এডিট করুন