DEV Community

thedevkim
thedevkim

Posted on

How i manage my react redux

Sometimes creating multiple actions, action types and reducers etc. on setting up a global value in react-redux.

This is how i manage my reducers

packages used:

redux
react-redux

First this is my folder structure
Image description

Folder Structure

 redux
  actions
   system
    actions.js
    actionTypes.js
   index.js (you can ignore this one)
   package.json (you can ignore this one)
  index.js (you can ignore this one)
  reducers
   index.js
   system.js
  index.js (you can ignore this one)
  store.js
Enter fullscreen mode Exit fullscreen mode

redux/store.js

import { createStore } from "redux";
import rootReducer from "./reducers";

export default createStore(rootReducer);

Enter fullscreen mode Exit fullscreen mode

redux/system/actions.js

import {
  SET_SYSTEM_DATA
} from "./actionTypes";


export const setSystemData = content => ({
  type: SET_SYSTEM_DATA,
  payload: {
      content
  }
})
Enter fullscreen mode Exit fullscreen mode

redux/system/actionTypes.js

export const SET_SYSTEM_DATA = "SET_SYSTEM_DATA"
Enter fullscreen mode Exit fullscreen mode

package.json

{
  "name": "redux_actions"
}
Enter fullscreen mode Exit fullscreen mode

redux/reducers/index.js

import { combineReducers } from "redux"
import system from "./system"

export default combineReducers({ system })
Enter fullscreen mode Exit fullscreen mode

redux/reducers/system.js

import {
  SET_SYSTEM_DATA,
} from "../actions/system/actionTypes"

const initialState = {
  is_global_value: false,

};

export default function(state = initialState, action) {
  switch (action.type) {
    case SET_SYSTEM_DATA: {
      const { content } = action.payload
      return {
        ...state,
        [content.key]: content.value
      };
    }
    default:
      return state
  }
}

Enter fullscreen mode Exit fullscreen mode

The setup is now finish.

This is how i use it.

//first the imports ofcourse
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {setSystemData} from 'redux_actions/system/actions'

const dispatch = useDispatch()

Enter fullscreen mode Exit fullscreen mode

If i want to change the is_global_value reducer value, I can just do it like this

dispatch(setSystemData({
 key: 'is_global_value',
 value: true  
}))
Enter fullscreen mode Exit fullscreen mode

Try listening to your reducers value by useSelector

import { useSelector } from 'react-redux'

const is_global_value = useSelector(state => state.system.is_global_value)

console.log(is_global_value)
Enter fullscreen mode Exit fullscreen mode

Let me know what you think. Thank you!

Top comments (2)

Collapse
 
devpaulodvo profile image
devpaulodvo

Does your folder structure necessary? Can you write some explanation each file? Thank you!

Collapse
 
devpaulodvo profile image
devpaulodvo

What a helpful tip you got there my friend! Thank you for this!