Redux Toolkit, Redux’un karmaşık görünen yapılarını daha basit ve anlaşılır hale getiren bir kütüphane.
npm i @reduxjs/toolkit
ile kuruyoruz.redux-thunk
gibi middleware’ler hazır geliyor.immer
kullandığı için doğrudan state
üzerinde mutate işlemi yapabiliyoruz (arka planda immutable’a çeviriyor).configureStore
kullanıyoruz. Bu, createStore
+ combineReducers
işini tek başına hallediyor.
import { configureStore } from "@reduxjs/toolkit";
import customerReducer from "./features/customerSlice";
import accountReducer from "./features/accountSlice";
const store = configureStore({
reducer: {
customer: customerReducer,
account: accountReducer,
},
});
export default store;
createSlice
reducer + action creator’ı birlikte tanımlar.
import { createSlice } from "@reduxjs/toolkit";
const customerSlice = createSlice({
name: "customer",
initialState: {
fullName: "",
nationalID: "",
createdAt: "",
},
reducers: {
createCustomer: {
reducer(state, action) {
state.fullName = action.payload.fullName;
state.nationalID = action.payload.nationalID;
state.createdAt = action.payload.createdAt;
},
prepare(fullName, nationalID) {
return {
payload: {
fullName,
nationalID,
createdAt: new Date().toISOString(),
},
};
},
},
updateName(state, action) {
state.fullName = action.payload;
},
},
});
export const { createCustomer, updateName } = customerSlice.actions;
export default customerSlice.reducer;
Burada dikkat:
prepare
kullanmazsak action sadece payload: value
alır.prepare
ile istediğimiz kadar argüman verip payload’ı kendimiz şekillendirebiliriz.API çağrıları gibi durumlar için createAsyncThunk
kullanıyoruz.
import { createAsyncThunk } from "@reduxjs/toolkit";
export const fetchAddress = createAsyncThunk(
"customer/fetchAddress",
async (nationalID) => {
const res = await fetch(`https://api.example.com/address/${nationalID}`);
const data = await res.json();
return { address: data.address };
}
);
Reducer tarafında otomatik pending
, fulfilled
, rejected
action’ları oluşuyor: