123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import {createStore, applyMiddleware, combineReducers} from 'redux';
- //import thunk from 'redux-thunk';
- import createSagaMiddleware from 'redux-saga';
- import { all, takeLatest, takeLeading, takeEvery, put } from 'redux-saga/effects';
- import {actionSearchResult} from '../actions';
- import { GraphQLClient } from 'graphql-request';
- const gql = new GraphQLClient('http://shop-roles.asmer.fs.a-level.com.ua/graphql')
- const sagaMiddleware = createSagaMiddleware()
- let store = createStore((state={}, {type, ...params}) => { //единственный редьюсер данного хранилища
- if (type === 'SEARCH_RESULT'){
- return {searchResult: {...params}}
- }
- return state//, в таком случае вызываются все редьюсеры, но далеко не всегда action.type будет относится к этому редьюсеру. Тогда редьюсер должен вернуть state как есть.
- }, applyMiddleware(sagaMiddleware))
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
- function* aWorker({timeout, message}){
- console.log('НАЧАЛО A WORKER ', timeout, message)
- yield put({type: 'LOG', text: `aWorker started with ${timeout}`})
- yield delay(timeout)
- console.log(message)
- }
- function* actionCheck(){
- yield takeLatest('ACTION_A', aWorker)
- }
- function* searchWorker({text}){
- yield put(actionSearchResult({payload: null})) //аналог dispatch(actionSearchResult({payload:null}))
- yield delay(2000) //аналог await
- let payload = yield gql.request( `
- query gf($query: String){
- GoodFind(query: $query){
- _id, name, description, price, images{
- _id, url
- }
- }
- }`, {query: JSON.stringify([
- {
- $or: [{name: `/${text}/`}, {description: `/${text}/`}] //регулярки пишутся в строках
- },
- {
- sort: [{name: 1}]} //сортируем по title алфавитно
- ])
- }) //аналог того же await
- yield put(actionSearchResult({payload})) //аналог dispatch()
- console.log('search end' , text)
- }
- function* searchCheck(){
- yield takeLeading('SEARCH', searchWorker)
- }
- function* logoutWorker(){
- yield put({type: 'PROMISE_CLEAR'})
- }
- function* logoutWatcher(){
- yield takeEvery('AUTH_LOGOUT', logoutWorker)
- }
- function* rootSaga(){
- yield all([
- actionCheck(),
- searchCheck(),
- logoutWatcher()
- //еще вотчеры если надо
- ])
- }
- sagaMiddleware.run(rootSaga)
- store.subscribe(()=> console.log(store.getState())) // подписка на обновления store
- store.dispatch({type: 'ACTION_A', timeout: 5000, message: 'HELLO WORLD 5sec'})
- store.dispatch({type: 'ACTION_A', timeout: 2000, message: 'WORLD HELLO 2sec'})
- export default store
|