D
D
Deniel2021-12-13 00:20:05
React
Deniel, 2021-12-13 00:20:05

Where to execute React asynchronous requests?

I have a react component, how do I implement an asynchronous request to the API (not in useEffect).
You need to send a request when the button is pressed, and then call the dispatch action'a, which will put the received data in the state (and in the same component where the button was pressed, draw the data from the state)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2021-12-13
@Casufi

https://github.com/reduxjs/redux-thunk
https://redux-saga.js.org/

E
egorovbyegorov, 2021-12-13
@egorovbyegorov

<code lang="javascript">
const reactCustomComponent = (props) => {
  const data = useSelector((state) => state.data)
  const onClickBtnHandler = (event) => {
    const response = асинхронный запрос(axios || fetch)
    dispatch action'a, (response.data) || .then(res => {
    dispatch action'a, (response.data)
  })
  }
  return (
    <>
      <Button onClick={onClickBtnHandler} />
      {
        data && data
      }
    </>
  )
}
</code>

But ideally, of course, if it is not there, set up redux-thunk and make asynchronous requests in actions

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question