A
A
alex4answ2020-04-25 16:59:47
React
alex4answ, 2020-04-25 16:59:47

Where to load initial data for React + Redux state?

I get the initial state from the API in the container component (smart component):

function App(props){
  useEffect(() => {
    if(!props.isLoaded){
      props.getInitialState();
    }
  });

  return <MyBlock data={props.data} />;
}

const mapStateToProps = store => {
  return { ...store};
};

const mapDispatchToProps = dispatch => {
  return {
    getInitialState: () => dispatch(getInitialState())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);


getInitialState - action creator:
function getInitialState() {
  return dispatch => {
    dispatch({
      type: 'GET_INITIAL_DATA'
    });

    fetch('url')
    .then(res => res.json())
    .then(data => {
      dispatch => {
        type: 'GET_INITIAL_DATA_SUCCESS',
        payload: data
      }
    });
    
  };
}

+ - in the working draft so, here I threw it for clarity

Is this the right approach?
What other options are there?

I saw how people try to make requests directly to the initialState in the Reducer, but it seems to me that this is not a completely correct and working approach.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question