Reputation: 1856
I have a left Sidebar that I want to share State of throughout my application so if user clicks on slider's button, user can make it hidden or show. Initially I plan to have it shown. I was following a Redux course and in the coure they did an example of fetching posts from API which is entirely different thant what I need so I am puzzled here...
So far, I created a folder called actions with 2 files, sliderActions.js
import { Slider } from "./types"
export function sliderUpdate() {
return function(dispatch) {
dispatch({
status: "hidden"
})
}
}
and types.js
export const Slider = "Slider";
reducers folder has two files index.js
import { combineReducers } from "redux"
import postReducer from "./postReducer"
export default combineReducers({
posts: postReducer
})
and postReducer.js
import { Slider } from "./../actions/types"
const initialState = {
Slider: "hide"
}
export default function(state = initialState, action) {
switch(action.type) {
default:
return state;
}
}
store.js file
import { createStore, applyMiddleware } from "redux"
import { thunk } from "redux-thunk"
import rootReducer from "./reducers"
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
applyMiddleware(...middleware)
)
export default store
and lastly I imported below two to the App.js
import { Provider } from "react-redux"
import { store } from "./store"
and wrapped my whole code inside return statement of App with a <Provider store={store}>
and </Provider>
I am entirely new to the redux and don't know how to get this working, any help would be appreciated!
Upvotes: 0
Views: 459
Reputation: 4481
Actions must have a type property that indicates the type of action being performed. Types should typically be defined as string constants.
So your actions file should be something like this
import { SLIDER } from "../constant/slide";
export function sliderUpdate() {
return function(dispatch) {
dispatch({
type: SLIDER,
status: "hidden"
});
};
}
Where the constant SLIDER
export const SLIDER = "SLIDER";
And the reducer should look like this
import { SLIDER } from "../constant/slide";
const initialState = {
Slider: "hide"
};
export default function(state = initialState, action) {
switch (action.type) {
case SLIDER:
return Object.assign({}, state, action.data);
default:
return state;
}
}
We don't mutate the state.So We create a copy with Object.assign()
where it will contain the new data.
Upvotes: 2
Reputation: 1489
Documentation says: Actions may not have an undefined "type" property.
Change your action in your sliderUpdate function and add 'type' key.
For example:
dispatch({
type: "SLIDER_BUTTON_CLICKED",
status: "hidden",
});
and now you want to change your postReducer to:
const initialState = {
slider: "opened"
}
export default function(state = initialState, action) {
switch(action.type) {
case "SLIDER_BUTTON_CLICKED": {
return {...state, slider: action.status}
}
default:
return state;
}
}
Upvotes: 1