DEV Community

Discussion on: Roll your Own Redux With useContext & useReducer

Collapse
 
inalbant profile image
Ibrahim

"It has no concept of middleware."

So can we not fetch API requests using this method?

Collapse
 
gsto profile image
Glenn Stovall • Edited

You could fetch API requests, but you couldn't do so using the dispatch method. no thunks or sagas here. Instead, you could make the API requests directly from your components or from helper functions, and then call dispatch when you handle the response.

Here's a new example of the createMessage function below that uses an API along with axios to post the new message to the server, and then update the state with the response:

  const createMessage = (e) => {
    e.preventDefault()
    axios
      .post('/messages', text) 
      .then(response => dispatch({
        type: 'ADD',
        payload: response.data,
      })
  }