Answer the question
In order to leave comments, you need to log in
How to cache server responses in Redux + React.js and where?
The bottom line is this: It is
necessary that when the action is called, a check is made whether the required object is already present in the store, if not, then load from the server.
It is not very clear how to check this in the action or where it should be done at all?
Tell me how to do it right?
Answer the question
In order to leave comments, you need to log in
I found a more suitable solution for my question, through redux-thunk, which passes the current state of the store as the second argument to the action
//redux-app/actions/LoadObject
export function LoadObject({ id }) {
return async ( dispatch, getState ) => {
let objectExist = getState().objects.some( _object => _object.id === id )
if( objectExist )
{
dispatch({
type: LOAD_OBJECT,
payload: {
id,
object: objectExist
}
})
} else {
dispatch({ type: LOAD_OBJECT_BEGIN })
let object = await ObjectApi.Load({ id })
dispatch({
type: LOAD_OBJECT,
payload: {
id,
object
}
})
}
}
}
middleware write.
But if the data is in the store, isn't it easier from the component to check for its presence and request only if it is not there?
As Aves
already wrote to you in the component, before calling the action, check if the data is already there - do not make a request. It might look like this:
loadData() {
if (state.data.length) {
// ничего не делай
} else {
this.props.callActionAndLoadData()
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question