3

Let's assume I have a component called BookOverview that displays details of a book.

I'm getting data with an action:

  componentDidMount() {
    this.props.getBook(areaId);
  }

And then I get the data with axios:

export const getBook = () => async dispatch => {
  const res = await axios.get(
    `${API}/${ENDPOINT}`
  );

  dispatch({
    type: GET_BOOK,
    payload: res.data
  });
};

How shall I change this code to:

  1. if redux store already have the book loaded - return it
  2. if no book is present in the store - call the relevant API?

What is the best practise to achieve that please?

Artur Stary
  • 724
  • 2
  • 13
  • 30

2 Answers2

4

You can have the getState inside your async action creator like this:

export const getBook = () => async (dispatch, getState) => {
  if(!getState().book /* check if book not present */) {
    const res = await axios.get(
      `${API}/${ENDPOINT}`
    );

    dispatch({
      type: GET_BOOK,
      payload: res.data
    });
  } else {
    dispatch({
      type: GET_BOOK,
      payload: getState().book
    });
  }
};

For More Async Actions-Redux

Suman Kundu
  • 1,702
  • 15
  • 22
  • Just for the case, the modern way to do that with amazin explain. https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk – soldy May 20 '22 at 21:51
1

You can try it this way:

  componentDidMount() {
    if(this.props.book==null){
       this.props.getBook(areaId);
    }
  }

I assumed that you have a property called book in your props. that populates from the particular reducer.
You have to subscribe the particular reducer to get the this.props.book - This gives the value that you have in your store.

isuruAb
  • 2,202
  • 5
  • 26
  • 39