DEV Community

loading...

Discussion on: Roll your Own Redux With useContext & useReducer

Collapse
gsto profile image
Glenn Stovall Author • 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,
      })
  }