I'm building an Android app using react-native
+ redux
+ immutable
I structured my app like this
/src
-/components
-/actions (where I have action types and actions)
-/reducers
-/api (I'm not sure if I'm doing this right)
Ok, so I have a action where I need to make an API call with fetch like this:
import * as types from './casesTypes'
export function getCases() {
return {
type: types.GET_CASES
}
}
This is the cases reducer:
const initialState = fromJS({
isLoading: false,
cases: null
})
export default function cases(state = initialState, action = {}) {
switch(action.type) {
case types.REQUEST_CASES:
return state.set('isLoading', true)
case types.RECIVE
return state.set('cases', //set here the array that I recive from api call)
default:
return state
}
}
So, the thing is that I dont really understand, where should I make the API call so that in the reducer I can merge my initial state with what I recive from the API call?
Your app structure is sound.
I also recommand the usage of redux-thunk to handle the dispatch. Here is how it would work in your case:
Let's say you have 'cases' as part of your state tree. I would put the API call in your action as you suggested to fetch new cases:
import * as types from './casesTypes'
export function getCases() {
return fetch(...)
...
.then((json) => {
dispatch({
type: types.RECEIVED_CASES,
isLoading: false,
cases: json,
}
}
And now in your reducer just get the newly dispatched action to merge the new cases with the state tree:
const initialState = fromJS({
isLoading: false,
cases: null
})
export default function cases(state = initialState, action = {}) {
switch(action.type) {
case types.REQUEST_CASES:
return state.set('isLoading', true)
case types.RECEIVED_CASES:
return Object.assign({}, state, {
cases: state.cases.merge(action.cases),
});
default:
return state
}
}
I am currently working with this structure and it works pretty well. Hope that helps!
You should try out redux-thunk or redux-saga, They are redux middlewares created to handle asynchronous actions like making an API call.
check out this project that used redux-thunk: sound-redux-native
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With