Redux: async / await и обработать событие - PullRequest
0 голосов
/ 21 декабря 2018

Это мой первый раз с Redux, и я застрял на данных выборки (и обработал событие).Я хочу получить данные в форме отправки.Я создаю код, как показано ниже и сейчас.Если я получу готовый для установки объект данных состояния с сервера, мне было проще, но сейчас я не знаю, как использовать функцию getWeather и чем заменить метод setState.Что мне нужно передать редуктору, чтобы получить правильные данные?

редуктор:

const initialState = {
  date: null,
  city: null,
  country: null,
  temp: null,
  temperatures: [],
  error: null,
  number: 0
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.GET_WEATHER:
      return {
        ...state
        // fetched data
      };
    default:
      return state;
  }
};

action:

export const getWeather = e => {
  return async dispatch => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    let temperatures = [];
    const API_CALL = await fetch(`url${city}url`);
    const data = await API_CALL.json();

    if (!city) {
      this.setState({error: "lorem ipsum"});
      return;
    }
    try {
      for (let i = 0; i < data.list.length; i += 8) {
        temperatures.push({
          date: data.list[i].dt_txt,
          temp: Math.round(data.list[i].main.temp),
          description: data.list[i].weather[0].description
        });
      }
      this.setState({
        date: data.list[0].dt_txt,
        city: data.city.name,
        country: data.city.country,
        temp: temperatures[0].temp,
        description: data.list[0].weather[0].description,
        temperatures: temperatures,
        error: null
      });
    } catch (error) {
      this.setState({ error: "lorem ipsum" });
    }
  };
};

store:

const composeEnharcers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(reducer, composeEnharcers(applyMiddleware(thunk)));

1 Ответ

0 голосов
/ 21 декабря 2018

Вместо setState вы бы инициировали disptach с типом, т.е. таким же, как тот, который используется в редукторах

export const getWeather = e => {
  return async dispatch => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    let temperatures = [];
    const API_CALL = await fetch(`url${city}url`);
    const data = await API_CALL.json();

    if (!city) {
      dispatch({type: actionTypes.GET_WEATHER, error: "lorem ipsum"});
      return;
    }
    try {
      for (let i = 0; i < data.list.length; i += 8) {
        temperatures.push({
          date: data.list[i].dt_txt,
          temp: Math.round(data.list[i].main.temp),
          description: data.list[i].weather[0].description
        });
      }
      dispatch({
        type: actionTypes.GET_WEATHER,
        payload: {
          date: data.list[0].dt_txt,
          city: data.city.name,
          country: data.city.country,
          temp: temperatures[0].temp,
          description: data.list[0].weather[0].description,
          temperatures: temperatures,
          error: null
        }
      });
    } catch (error) {
      dispatch({type:actionTypes.GET_WEATHER, error: "lorem ipsum" });
    }
  };
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.GET_WEATHER:
      return {
        ...state
        ...action.payload
      };
    default:
      return state;
  }
};
...