How to specify load status for an asynchronous action during the first render using shorthand

Say I have a redux module that looks like this:

import fetch from 'isomorphic-fetch';

// CONSTANTS
const LOAD = 'LOAD';
const LOAD_SUCCESS = 'LOAD_SUCCESS';

// REDUCER
const initialState = { loading: false, data: [] };

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case LOAD: return { ...state, loading: true };
    case LOAD_SUCCESS: return { ...state, loading: false, data: action.data };
    default: return state;
  }
}

// ACTION CREATORS
function requestLocations() {
  return { type: LOAD };
}

function receiveLocations(json) {
  return { type: LOAD_SUCCESS, data: json };
}

export function fetchLocations() {
  return function (dispatch) {
    dispatch(requestLocations());

    return fetch('http://myurl')
      .then(response => response.json())
      .then(json => dispatch(receiveLocations(json)));
  };
}

I am struggling with state loadingin the first render if I make an asynchronous call in the WillMount component. Imagine my component looks like this (simplified for brevity):

export default class LocationContainer extends React.Component {
  componentWillMount() {
    fetchLocations(); // already bound and injected via connect.
  }

  render() {
    const { loading, data } = this.props; // injected via connect from reducer above.
    if (loading) {
      return <Spinner />;
    } else {
      return <LocationExplorer locations={ data } />;
    }
  }
}

, , , LocationContainer, loading , data . componentWillMount LOAD , loading, true, , . LocationExplorer , Spinner , loading - . , , firstRender = true.

+4
2

loading data:

const initialState = { loading: false, data: [] };

loading data , , :

if (loading && data.length === 0) {
  return <Spinner />;
} else {

, componentDidMount componentWillMount.

+6

componentWillMount. , . .

store.dispatch(fetchLocations());
ReactDOM.render(<App store={store} />, mountpoint);
0

Source: https://habr.com/ru/post/1619592/


All Articles