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
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
redux/store.js
import { createStore } from "redux";
import rootReducer from "./reducers";
export default createStore(rootReducer);
redux/system/actions.js
import {
SET_SYSTEM_DATA
} from "./actionTypes";
export const setSystemData = content => ({
type: SET_SYSTEM_DATA,
payload: {
content
}
})
redux/system/actionTypes.js
export const SET_SYSTEM_DATA = "SET_SYSTEM_DATA"
package.json
{
"name": "redux_actions"
}
redux/reducers/index.js
import { combineReducers } from "redux"
import system from "./system"
export default combineReducers({ system })
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
}
}
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()
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
}))
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)
Let me know what you think. Thank you!
Top comments (2)
Does your folder structure necessary? Can you write some explanation each file? Thank you!
What a helpful tip you got there my friend! Thank you for this!