Skip to content

Instantly share code, notes, and snippets.

@imparvez
Created July 18, 2020 15:58
Show Gist options
  • Save imparvez/1481a14e020ac21ffa4f3cb562ad5745 to your computer and use it in GitHub Desktop.
Save imparvez/1481a14e020ac21ffa4f3cb562ad5745 to your computer and use it in GitHub Desktop.
React Redux Async Await
import axios from 'axios'
import * as actions from './actions'
export function suggestedSearch() {
return async dispatch => {
try {
dispatch(actions.suggestedSearchLoading())
const url = 'https://0b6c4e73-c7fd-4eab-b3ad-89e11db59c58.mock.pstmn.io/search'
const json = await axios.get(url)
if(json.status === 200 && json.data) {
dispatch(actions.suggestedSearchSuccess(json.data))
} else {
dispatch(actions.suggestedSearchFailure('Something went wrong. Please try again later.'))
}
} catch(e) {
dispatch(actions.suggestedSearchFailure(e))
}
}
}
import * as types from './types'
export function suggestedSearchLoading() {
return {
type: types.SUGGESTED_SEARCH_LOADING
}
}
export function suggestedSearchSuccess(data) {
return {
type: types.SUGGESTED_SEARCH_SUCCESS,
data
}
}
export function suggestedSearchFailure(error) {
return {
type: types.SUGGESTED_SEARCH_FAILURE,
error
}
}
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Root from './roots'
ReactDOM.render(
<Root>
<App />
</Root>,
document.getElementById('root')
);
import { combineReducers } from 'redux'
import searchResultContent from './searchReducer'
const searchReducer = combineReducers({
searchResultContent
})
export default searchReducer
import React from 'react'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk';
import reducers from './rootReducer';
export default ({ children, initialState = {} }) => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
initialState,
composeEnhancers(applyMiddleware(thunk))
)
return (
<Provider store={store}>
{children}
</Provider>
)
}
import * as types from './types'
const searchInitialState = {
data: {},
loading: true,
error: false,
errorMessage: ''
}
export default function searchResultContent(state = searchInitialState, action) {
switch(action.type) {
case types.SEARCH_FILTER_LOADING: {
return {
...state,
loading: true,
error: false,
errorMessage: ''
}
}
case types.SEARCH_FILTER_SUCCESS: {
console.log('DATA => ', action.data)
return {
...state,
data: action.data,
loading: false,
error: false
}
}
case types.SEARCH_FILTER_FAILURE: {
return {
...state,
loading: false,
errorMessage: action.error || '',
error: true
}
}
default:
return state
}
}
export const SUGGESTED_SEARCH_LOADING = 'SUGGESTED_SEARCH_LOADING'
export const SUGGESTED_SEARCH_SUCCESS = 'SUGGESTED_SEARCH_SUCCESS'
export const SUGGESTED_SEARCH_FAILURE = 'SUGGESTED_SEARCH_FAILURE'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment