0

I have React app with Redux that has following structure:

<ComponentParent>
<ComponentA></ComponentA>
<ComponentB></ComponentB>
</ComponentParent>

In component A an ComponentDidMount, a fetch is called and data is return async-ly. Reducer is then called to add data to the store. Component B then accesses the store to access data added by A to the store.

Predictably Component B accesses the data before Component A had a change to write data to the store (because data is coming from aync fetch).

Question:

  1. what is a proper way to design such interaction?
  2. Do I need use approach similar to react redux with asynchronous fetch ? Note that in Reducer I just store data returned async-ly by Component A, unlike in the link

Thanks

0

2 Answers 2

2

Set a default state to your componentB for it to load while awaiting results from your fetch.

In your fetch action, assuming you use redux-thunk:

let fetchData = () => async dispatch => {
 let res = await fetchFromDataSource();
 dispatch({
  type: UPDATE_STATE,
  payload: res
 }) 
};

Your component B should be linked up to the store. Upon dispatch update, it should trigger your componentB to reload via ComponentDidUpdate.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. I don't want to use await thought as it will block. I will try Steven's approach, but first I need wrap my brains around thunk
Thunk (without await) was the answer: daveceddia.com/where-fetch-data-redux
0

I like the pattern of creating an initial state for the object in the reducer, so that any component accessing it gets that initial state first, and can later update based on a post-fetch state.

xReducer.js

const initState = {
  // Initial state of object
};
export default function xReducer(state=initState, action) {
  switch (action.type) {
    case actionTypes.MY_POST_FETCH_ACTION_TYPE:
      return {
          ...state,
          // state override
      };
      default:
        return state;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.