2

I have a form, and I wanted to call a hooks function usePostAddList() in the component AddList() inside the function onSubmit(). basically the usePostAddList() is to make a POST request.

Here's the code for the AddList():

AddList.jsx

export default function AddList() {
..
..
const onSubmit = (e) => {
    e.preventDefault()

    const data = [
      {
        komoditas,
        areaKota,
        areaProvinsi,
        price,
        tglParsed,
      },
    ]

    // I called it here and it show an error
    usePostAddList(data)
}
..
..
}

Reducer/index.js

export function usePostAddList(data) {
  const [state, dispatch] = React.useReducer(reducer, initState)

  React.useEffect(() => {
    dispatch({ type: ACTIONS.MAKE_REQUEST })
    store
      .append("Sheet2", data)
      .then((res) =>
        dispatch({
          type: ACTIONS.ADD_LIST,
          payload: res,
        })
      )
      .catch((e) => {
        return dispatch({
          type: ACTIONS.GET_ERRORS,
          payload: e,
        })
      })
  }, [])

  return state
}

I have read many solutions like I must write "use" for the name of the function, capitalize the function AddList, but still got this error:

React Hook "usePostAddList" is called in function "onSubmit" which is neither a React function component or a custom React Hook function

but if I called the usePostAddList() like this code below somehow it worked :

AddList.jsx

export default function AddList() {
   const { lists, loading, errors } = usePostAddList("test")

   return (
      ...
   )
}

but it didn't solve my problem

panji gemilang
  • 759
  • 2
  • 10
  • 25

1 Answers1

6

You can only use hooks inside functional components and at the top of your component. Check rules of hooks for more information on why.

You can use your custom hook as follows:

export default function AddList() {
 const [data,setData] = useState()
 const { lists, loading, errors } = usePostAddList(data)

 return (
  ...
 )
}

And update your data at onSubmit function:

const onSubmit = (e) => {
 e.preventDefault()

 const data = [
  {
    komoditas,
    areaKota,
    areaProvinsi,
    price,
    tglParsed,
   },
 ]

 // Call set data
 setData(data)
}
Çağatay Sel
  • 801
  • 7
  • 14