Redux-Saga Middleware -2 HandsOn

Redux-saganın teori kısmının anlatıldığı ilk yazımız için.

http://buraktunali.blogspot.com/2021/07/redux-saga-middleware-1-teori.html


Redux-saga işlemleri için bir backend hazırlayalım. 

Node.js de yapacağımız bu backend için express generator u kullanabilirsiniz.

https://expressjs.com/en/starter/generator.html

Şu an için tek bir servis yeterli.

router klasörü altında index dosyasına servisimizi koyalım.

router.get('/test', function(req, res, next) {

   res.json({ Hello : 'World' });

});

node app.js diyerek projemizi kaldıralım. 


Öncelikle React projemizin full kodunu ekliyorum.

Gmotes/Redux-Saga (github.com)


Şimdi ise react projemizi oluşturalım.

npx create-react-app redux-saga-app


İhtiyacımız olan paketler aşağıdaki gibi package.json a ekleyip npm install yapalım.

    "axios": "^0.21.1",

    "react": "^17.0.2",

    "react-dom": "^17.0.2",

    "react-redux": "^7.2.4",

    "react-scripts": "4.0.3",

    "redux": "^4.1.0",

    "redux-devtools-extension": "^2.13.9",

    "redux-saga": "^1.1.3",

    "redux-saga-effects": "^1.1.0"





Soldaki gibi bir dosya yapısı kuralım. Action ve Reducer yapımız klasik. Saga için iki dosya ekledik. Ayrıca api çağrısı yapacak callApi.js dosyası oluşturuyoruz.







Root altındaki index.js dosyasını store olarak ekliyoruz.

import store from './store';

ReactDOM.render( <Provider store={store}> <React.StrictMode> <App /> </React.StrictMode> </Provider>, document.getElementById('root') );


Yazımızın konusu olan TEST_REQUEST actionını karşılayan saga yapısı aşağıdaki gibi. Bu yapıyı middleware den dinleyecek şekilde index.js e oradan da store a ekliyoruz. Bu kısımlar için github ı kontrol edebilirsiniz.


import { all,call,fork,takeLatest } from 'redux-saga/effects';

import {callApi} from '../../util/callApi';

function* watchTestRequest() {

    yield takeLatest('TEST_REQUEST', getTestRequest);

}

function* getTestRequest(action) {

      yield call(callApi,

        'get',

        'test',

      ); 

}

export default function* testSaga() {

    yield all([

      fork(watchTestRequest)

    ])

  }

Projeyi çalıştırdığınız da önce reducer sonra da saga nın çalıştığını göreceksiniz.


Herkese kolaylıklar.



Yorumlar

Bu blogdaki popüler yayınlar

IONIC BAŞLANGIÇ

Cannot resolve the collation conflict between “Turkish_CI_AS” and “SQL_Latin1_General_CP1_CI_AS” in the equal to operation

Golang working with interfaces and functions -3