'useCallback to fetch data on button click
I have a scenario where I am to fetch data on a button click and store it in a context variable. Please check the code below:
const [products, setProducts] = useState([]);
const handleButtonClick= useCallback(() => {
if (countryCode) {
async function getproducts() {
try {
const apiData = await fetch(URL);
const jsonData = await apiData.json();
setProducts(jsonData);
} catch (error) {
console.error(error);
}
}
getproducts();
}
}, [targetGroup,countryCode]);
I would use this callback function: handleButtonClick() on the button onClick(). I'm still new to React and I'm sometimes confused with React hooks. Is this a correct approach or is there no need for a callback function at all, just a normal function would do?
Solution 1:[1]
You don't need useCallback for this function, you can write a normal function and use it like this:
<button onClick={handleButtonClick}>Click me</button>
Solution 2:[2]
I think your code is okay, but I would like to refactor your code.
import React from 'react';
import { getProducts } from '~/apis/product';
const SomeComponent = () => {
const [products, setProducts] = React.useState([]);
const handleButtonClick = React.useCallback(async ()=>{
if(countryCode) {
const _products = await getProducts();
setProducts(_products);
}
}, [countryCode]); // I don't know what is countryCode but I guess it must be a state, so you need to add that.
return (<div>Some Component</div>);
}
export default SomeComponent;
You can separate API function and component. ~/apis/product.js
export async function getproducts() {
try {
const apiData = await fetch(`SOME YOUR URL`);
const jsonData = await apiData.json();
return jsonData;
} catch (error) {
console.error(error);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ssunsset |
| Solution 2 | kyun |
