Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching data from store if exists or call API otherwise in React

Tags:

reactjs

redux

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?

like image 794
Artur Stary Avatar asked Oct 25 '25 18:10

Artur Stary


1 Answers

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

like image 86
Suman Kundu Avatar answered Oct 28 '25 07:10

Suman Kundu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!