A
A
Alexander Antonov2016-11-17 23:56:39
JavaScript
Alexander Antonov, 2016-11-17 23:56:39

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

4 answer(s)
A
Alexander Antonov, 2016-11-18
@undermuz

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
                }
            })
        }
    }
}

A
Aves, 2016-11-18
@Aves

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?

M
Maxim, 2016-11-18
@maxfarseer

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()
  }
}

V
vsuhachev, 2016-11-18
@vsuhachev

It's normal to set up HTTP caching (ETag, quick response 304, keep-alive) and the browser will cache everything itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question