- Joined
- Dec 2, 2022
- Messages
- 7
- Reaction score
- 1
Hello to all React experts! I'm building a React/Redux/RTK application, and this problem worries me. I have all api endpoints to make CRUD operations.
And all of my logic to make CRUD operations looks similar, for example the common hook to add a variant and get all variants from the API looks like this:
Is it right way to communicate with API? For example I'm set a post query to create something, right? and once this something was created I call the hook to get all data from the API again to show to a user updated data, right?
I think there is a better way to do that, for example I can communicate with the store, and store communicate with API. Can somebody share with me any guide related with my problem?
Thank you
And all of my logic to make CRUD operations looks similar, for example the common hook to add a variant and get all variants from the API looks like this:
JavaScript:
import api from 'api/axiosBase'
import { useCallback, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from 'store/index'
import { addVariants } from 'store/features/variants'
const useVariantsByExpSlug = () => {
const dispatch = useDispatch()
const [error, setError] = useState(null)
const [isLoading, setIsLoading] = useState(false)
const { variants } = useSelector((state: RootState) => state.variants)
const getVariantsByExpSlug = useCallback(
async (slug: string) => {
try {
setIsLoading(true)
const { data } = await api.get(`variants/${slug}`)
dispatch(addVariants(data))
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
setError(error)
} finally {
setIsLoading(false)
}
},
[dispatch],
)
const handleAddVariant = useCallback(
async (params: { ratio: number; experiment_slug: string }) => {
try {
const { data } = await api.post('variants', params)
dispatch(addVariants([...variants, data]))
return data
} catch (error) {
console.error('Error:', error)
}
},
[dispatch, variants],
)
if (error) throw error
return {
getVariantsByExpSlug,
handleAddVariant,
error,
isLoading,
}
}
export default useVariantsByExpSlug
Is it right way to communicate with API? For example I'm set a post query to create something, right? and once this something was created I call the hook to get all data from the API again to show to a user updated data, right?
I think there is a better way to do that, for example I can communicate with the store, and store communicate with API. Can somebody share with me any guide related with my problem?
Thank you