In React applications, where do you put the networking code. I have seen code as shown below. But in this case, the request is right there in the component and cannot be reused. I know I can use Redux but the products array is not meant to be shared globally with other components.
function App() {
const [products, setProducts] = useState([])
useEffect(() => {
const getProducts = async () => {
const response = await fetch(`someurl.com/products`)
const products = await response.json()
setProducts(products)
}
getProducts()
}, [])
const productItems = products.map(product => {
return <li key = {product.id}>{product.title}</li>
})
return (
<ul>
{productItems}
</ul>
);
}
CodePudding user response:
I think, there is a lot of ways, of app architecture design for handling this scenario, depending of app scale.
The simpiest way to reuse and incapsulate such behaviour would be custom hook:
const getProducts = async () => {
const response = await fetch(`someurl.com/products`)
const products = await response.json()
return products
}
export const useProducts = () =>
{
const [products, setProducts] = useState([])
useEffect(() => {
getProducts().then(setProducts)
}, [])
return products
}
function App() {
const products = useProducts()
const productItems = products.map(product => {
return <li key = {product.id}>{product.title}</li>
})
return (
<ul>
{productItems}
</ul>
);
}