index.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {createStore, applyMiddleware, combineReducers} from 'redux';
  2. //import thunk from 'redux-thunk';
  3. import createSagaMiddleware from 'redux-saga';
  4. import { all, takeLatest, takeLeading, takeEvery, put } from 'redux-saga/effects';
  5. import {actionSearchResult} from '../actions';
  6. import { GraphQLClient } from 'graphql-request';
  7. const gql = new GraphQLClient('http://shop-roles.asmer.fs.a-level.com.ua/graphql')
  8. const sagaMiddleware = createSagaMiddleware()
  9. let store = createStore((state={}, {type, ...params}) => { //единственный редьюсер данного хранилища
  10. if (type === 'SEARCH_RESULT'){
  11. return {searchResult: {...params}}
  12. }
  13. return state//, в таком случае вызываются все редьюсеры, но далеко не всегда action.type будет относится к этому редьюсеру. Тогда редьюсер должен вернуть state как есть.
  14. }, applyMiddleware(sagaMiddleware))
  15. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  16. function* aWorker({timeout, message}){
  17. console.log('НАЧАЛО A WORKER ', timeout, message)
  18. yield put({type: 'LOG', text: `aWorker started with ${timeout}`})
  19. yield delay(timeout)
  20. console.log(message)
  21. }
  22. function* actionCheck(){
  23. yield takeLatest('ACTION_A', aWorker)
  24. }
  25. function* searchWorker({text}){
  26. yield put(actionSearchResult({payload: null})) //аналог dispatch(actionSearchResult({payload:null}))
  27. yield delay(2000) //аналог await
  28. let payload = yield gql.request( `
  29. query gf($query: String){
  30. GoodFind(query: $query){
  31. _id, name, description, price, images{
  32. _id, url
  33. }
  34. }
  35. }`, {query: JSON.stringify([
  36. {
  37. $or: [{name: `/${text}/`}, {description: `/${text}/`}] //регулярки пишутся в строках
  38. },
  39. {
  40. sort: [{name: 1}]} //сортируем по title алфавитно
  41. ])
  42. }) //аналог того же await
  43. yield put(actionSearchResult({payload})) //аналог dispatch()
  44. console.log('search end' , text)
  45. }
  46. function* searchCheck(){
  47. yield takeLeading('SEARCH', searchWorker)
  48. }
  49. function* logoutWorker(){
  50. yield put({type: 'PROMISE_CLEAR'})
  51. }
  52. function* logoutWatcher(){
  53. yield takeEvery('AUTH_LOGOUT', logoutWorker)
  54. }
  55. function* rootSaga(){
  56. yield all([
  57. actionCheck(),
  58. searchCheck(),
  59. logoutWatcher()
  60. //еще вотчеры если надо
  61. ])
  62. }
  63. sagaMiddleware.run(rootSaga)
  64. store.subscribe(()=> console.log(store.getState())) // подписка на обновления store
  65. store.dispatch({type: 'ACTION_A', timeout: 5000, message: 'HELLO WORLD 5sec'})
  66. store.dispatch({type: 'ACTION_A', timeout: 2000, message: 'WORLD HELLO 2sec'})
  67. export default store