Redux Toolkit with Node js
Tags: javascript, webdev, node, redux
Published: 2022-12-26 16:10:17

in this article  we will explain how to use **Redux toolkit** with **Node js**.

if you don't know how to create node js application please follow this article [https://levelup.gitconnected.com/set-up-and-run-a-simple-node-server-project-38b403a3dc09](url)

if you don't know what's Redux toolkit is please take the tutorial in them official website [https://redux-toolkit.js.org/introduction/getting-started](url)

**to not make it complicated for you this article is for who face problems to mange them state in node js applications.**

**Now let's start**
1- install Redux toolkit inside your application
using npm  `npm install @reduxjs/toolkit`  
or yarn `yarn add @reduxjs/toolkit`. 

2- create reducer in your application and give it a name in my case i give it name (users) and add the following code.

```
const {createSlice,createAsyncThunk} = require('@reduxjs/toolkit');
const axios = require("axios");



const getinfoFromServer = createAsyncThunk('getSominfoFromFakeAPI',async()=>{
const response = await axios.get('https://dummyjson.com/products').then(data => data);
return response.data.products;
})

 

const initialState = {
  value: 60,
  info:null
}

const counterSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
  extraReducers:(builder) =>{
      builder.addCase(getinfoFromServer.fulfilled,(state ,action)=>{
           state.info = action.payload;
      })
  }
});
const selectCount = (state) => state.users;

// Action creators are generated for each case reducer function
const{ increment, decrement, incrementByAmount } = counterSlice.actions;
// Action creators are generated for each case reducer function
exports.counterSlice = counterSlice;
exports.selectCount = selectCount;
exports.reducer = counterSlice.reducer;
exports.increment = increment;
exports.decrement = decrement;
exports.incrementByAmount = incrementByAmount;
exports.getinfoFromServer = getinfoFromServer;
```
**(code explanition)**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yg4l0adwwmi2ybb7wuyr.png)
here we import createSlice and createAsyncThunk 
and we import axios.

**reducer file is build as following ** 
```
const {createSlice,createAsyncThunk} = require('@reduxjs/toolkit');
const axios = require("axios");



// any async functions using createAsyncThunk you wanna add to your application

 

const initialState = {
  // add any intial value you would like to add to start your application with
}

const counterSlice = createSlice({
  name: 'users',// add any name you would like 
  initialState, // add initialState as your state you can add any object of any state you would like 
  reducers: {
    /* add the reducer to get and edite and delete your initialState  
       but all reducer you will add here only to be pure functions no async functions it's allowed here 
       if you would like to 
    */
  },
  extraReducers:(builder) =>{
  // to add the statge of all async functions and them reducer the same as normal reducer almost
  }
});
const selectCount = (state) => state.users;  /*
 here you export your state of users state.users and the name i make it users to can see the name in 
 create slice is so important to export your state so pay attantion to that 
 */ 

// Action creators are generated for each case reducer function
const{ increment, decrement, incrementByAmount } = counterSlice.actions;
// Action creators are generated for each case reducer function
/* this how you export your normal and asnyc reducer and the counter slice as the same */
exports.counterSlice = counterSlice;
exports.selectCount = selectCount;
exports.reducer = counterSlice.reducer;
exports.increment = increment;
exports.decrement = decrement;
exports.incrementByAmount = incrementByAmount;
exports.getinfoFromServer = getinfoFromServer;


```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9318wr3ff27a4fz29kaz.png)
this is how to use createAsyncThunk inside Redux toolkit 
 `createAsyncThunk()` have 2 arguments first the name of the actions **you can put any name you like** the second one something it will take time like to fetch some data from the server **and it has to return something cause what will gonna happen the value it will go in the extra reducer down** (in Redux toolkit we not need to use Redux Thunk)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7n17v3zemb45rtssqlw.png)

the returned value from getSominfoFromFakeAPI it will be in `action.playload` in the fulfilled mode, actually in the extra reducer it's supposed to be 3 cases like this example 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onw39wkn7zth13l4x6aj.png)
you can check more in this link [https://redux-toolkit.js.org/api/createAsyncThunk](url)

   

3- create file in your project by name store.js
and add the following code.

```
const {configureStore} = require('@reduxjs/toolkit'); 
const {reducer} = require('./ReduxReducer/users');

 const store = configureStore({
    reducer: {
        users:reducer //the name of users it must be the same as in the createSlice one 
    },
  });

module.exports = store;
```

**Now let's use our redux state and them reducers** 
```
const {selectCount} = require('../ReduxReducer/users');
const store = require('../store'); // import store from store file 
const {increment,getinfoFromServer} = require('../ReduxReducer/users');

const userData = (req , res, next) =>{
    // use the getState from store to get our state selectCount from  our reducer users 
   const value = store.getState(selectCount); 
    
   res.status(200).json({message:'the request is scssful', data:value.users});
};


const editeusers = (req , res , next) => {
    // using  dispatch from store and put inside it increment from our reducer users
    store.dispatch(increment());
    const value = store.getState(selectCount); 
    res.status(200).json({message:'the request is scssful', data:value.users});
}; 

const testThunk = async(req,res,next)=>{
    // here we use the async reducer from our reducer users who using createAsyncThunk and extra reducer 
        await store.dispatch(getinfoFromServer()); 
        const value = store.getState(selectCount); 
        res.status(200).json(value);
    

    
}
 exports.userData = userData;
 exports.editeusers = editeusers;
 exports.testThunk = testThunk;
```
 the source code you can find it here [https://github.com/Mohamed1255847/Redux-Tookit-with-NodeJs-.git](url)

I hope that was helpful for you.      
All the best  
Mohamed Afify