React+Redux+RTK

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:


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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top