A
A
ArtemKalinin25032019-04-02 23:40:25
React
ArtemKalinin2503, 2019-04-02 23:40:25

Why is console.log called twice when getting data from Saga?

- There is an express server that receives data from the Yandex Weather API
5ca3cb0b03669307590885.png
- There is a saga that receives a response from the server with data:
5ca3ca8bb0129844715433.png
- There is a component in which an action is called that calls this saga:
5ca3cb61a17f2574666958.png
- Actions are described in . reducer
5ca3cbd9b07cf737659434.png
- But it turns out that first an empty state comes, and only then the data comes to the state a second time, as a result, I can’t work with the data when the page loads, please help ....
5ca3ca1000a0c733302305.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-03
@ArtemKalinin2503

1. The componentDidMound method is called after the component is mounted. Naturally, there can be no data during the first render.
2. The request for data is asynchronous, you cannot know at what point the response will come. Therefore, it is a good idea to store and use the boot state key. You have it in the code, but it is not used (isGettingCityWeather, in my example it is isFetching)
3. The loading state key is not updated when data is received and an error occurs. Fix it.
4. city comes in the form of an object, but in the initial state you have an array. Fix it.
Solution example:

const initialState = {
  isFetching: false,
  city: {},
  error: null,
};

const weatherReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'GET_WEATHER_REQUEST':
      return {
        ...state,
        isFetching: true,
        error: null,
      };
    case 'GET_WEATHER_SUCCEEDED':
      return {
        ...state,
        isFetching: false,
        city: action.payload,
      };
    case 'GET_WEATHER_FAILED':
      return {
        ...state,
        isFetching: false,
        error: action.payload,
      };
    default:
      return state;
  }
}

render() {
  const { isFetching, city, error, getWeather } = this.props;
  
  if (isFetching) return <div>Loading...</div>;

  if (error) return <TryAgain error={error} handler={getWeather} />;
  
  return <div>{city.now_dt}</div>;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question