<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mohamed Saadawy </title>
    <description>The latest articles on DEV Community by Mohamed Saadawy  (@mohamed1255847).</description>
    <link>https://dev.to/mohamed1255847</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F983143%2F4b079f04-585c-476e-a63b-60b20b1d19b4.jpeg</url>
      <title>DEV Community: Mohamed Saadawy </title>
      <link>https://dev.to/mohamed1255847</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mohamed1255847"/>
    <language>en</language>
    <item>
      <title>Redux Toolkit with Node js</title>
      <dc:creator>Mohamed Saadawy </dc:creator>
      <pubDate>Mon, 26 Dec 2022 16:10:17 +0000</pubDate>
      <link>https://dev.to/mohamed1255847/redux-toolkit-with-node-js-4c3m</link>
      <guid>https://dev.to/mohamed1255847/redux-toolkit-with-node-js-4c3m</guid>
      <description>&lt;p&gt;in this article  we will explain how to use &lt;strong&gt;Redux toolkit&lt;/strong&gt; with &lt;strong&gt;Node js&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;if you don't know how to create node js application please follow this article &lt;a href="https://dev.tourl"&gt;https://levelup.gitconnected.com/set-up-and-run-a-simple-node-server-project-38b403a3dc09&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;if you don't know what's Redux toolkit is please take the tutorial in them official website &lt;a href="https://dev.tourl"&gt;https://redux-toolkit.js.org/introduction/getting-started&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;to not make it complicated for you this article is for who face problems to mange them state in node js applications.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now let's start&lt;/strong&gt;&lt;br&gt;
1- install Redux toolkit inside your application&lt;br&gt;
using npm  &lt;code&gt;npm install @reduxjs/toolkit&lt;/code&gt;&lt;br&gt;&lt;br&gt;
or yarn &lt;code&gt;yarn add @reduxjs/toolkit&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;2- create reducer in your application and give it a name in my case i give it name (users) and add the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {createSlice,createAsyncThunk} = require('@reduxjs/toolkit');
const axios = require("axios");



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



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

const counterSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    increment: (state) =&amp;gt; {
      // 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) =&amp;gt; {
      state.value -= 1
    },
    incrementByAmount: (state, action) =&amp;gt; {
      state.value += action.payload
    },
  },
  extraReducers:(builder) =&amp;gt;{
      builder.addCase(getinfoFromServer.fulfilled,(state ,action)=&amp;gt;{
           state.info = action.payload;
      })
  }
});
const selectCount = (state) =&amp;gt; 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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;(code explanition)&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyg4l0adwwmi2ybb7wuyr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyg4l0adwwmi2ybb7wuyr.png" alt="Image description" width="593" height="54"&gt;&lt;/a&gt;&lt;br&gt;
here we import createSlice and createAsyncThunk &lt;br&gt;
and we import axios.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;reducer file is build as following *&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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) =&amp;gt;{
  // to add the statge of all async functions and them reducer the same as normal reducer almost
  }
});
const selectCount = (state) =&amp;gt; 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;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9318wr3ff27a4fz29kaz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9318wr3ff27a4fz29kaz.png" alt="Image description" width="776" height="115"&gt;&lt;/a&gt;&lt;br&gt;
this is how to use createAsyncThunk inside Redux toolkit &lt;br&gt;
 &lt;code&gt;createAsyncThunk()&lt;/code&gt; have 2 arguments first the name of the actions &lt;strong&gt;you can put any name you like&lt;/strong&gt; the second one something it will take time like to fetch some data from the server &lt;strong&gt;and it has to return something cause what will gonna happen the value it will go in the extra reducer down&lt;/strong&gt; (in Redux toolkit we not need to use Redux Thunk)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk7n17v3zemb45rtssqlw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk7n17v3zemb45rtssqlw.png" alt="Image description" width="776" height="115"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;the returned value from getSominfoFromFakeAPI it will be in &lt;code&gt;action.playload&lt;/code&gt; in the fulfilled mode, actually in the extra reducer it's supposed to be 3 cases like this example &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fonw39wkn7zth13l4x6aj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fonw39wkn7zth13l4x6aj.png" alt="Image description" width="738" height="290"&gt;&lt;/a&gt;&lt;br&gt;
you can check more in this link &lt;a href="https://dev.tourl"&gt;https://redux-toolkit.js.org/api/createAsyncThunk&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;3- create file in your project by name store.js&lt;br&gt;
and add the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Now let's use our redux state and them reducers&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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) =&amp;gt;{
    // 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) =&amp;gt; {
    // 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)=&amp;gt;{
    // 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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the source code you can find it here &lt;a href="https://dev.tourl"&gt;https://github.com/Mohamed1255847/Redux-Tookit-with-NodeJs-.git&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope that was helpful for you.&lt;br&gt;&lt;br&gt;
All the best&lt;br&gt;&lt;br&gt;
Mohamed Afify&lt;/p&gt;

</description>
      <category>ai</category>
    </item>
  </channel>
</rss>
