Skip to content

Instantly share code, notes, and snippets.

@Ahrengot
Created March 21, 2017 10:00
Show Gist options
  • Save Ahrengot/a0565b20c914771a5b6efd92119ef62d to your computer and use it in GitHub Desktop.
Save Ahrengot/a0565b20c914771a5b6efd92119ef62d to your computer and use it in GitHub Desktop.
Redux Saga example
import {
call,
put,
takeLatest
} from 'redux-saga/effects'
import {
UPDATE_QUERY,
WEATHER_DATA_REQUESTED,
WEATHER_DATA_RECEIVED,
WEATHER_DATA_FAILED,
store
} from './update'
/**
* Weather search saga
*/
const getWeatherApiUrl = city => {
city = encodeURIComponent(city);
const query = `select item,astronomy,units from weather.forecast where woeid in (select woeid from geo.places(1) where text="${ city }") and u="c"`;
return `https://query.yahooapis.com/v1/public/yql?q=${ escape(query) }&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`;
}
const httpGet = function (requestUrl) {
return fetch(requestUrl)
.then( response => response.json() )
.catch( error => ({ error }) )
}
const fetchWeather = function* (action) {
try {
const query = store.getState().weather.query;
const url = getWeatherApiUrl( query );
const result = yield call( httpGet, url )
yield put({
type: WEATHER_DATA_RECEIVED,
payload: {
result: { ...result.query.results.channel.item,
units: result.query.results.channel.units,
astronomy: result.query.results.channel.astronomy
}
}
})
}
catch (e) {
yield put({
type: WEATHER_DATA_FAILED,
payload: { loadError: e.message }
})
}
}
export const searchSaga = function* () {
yield takeLatest( WEATHER_DATA_REQUESTED, fetchWeather );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment