Reputation: 9417
Currently I am using an action
to pass a data value, as so...
<button onClick={() => this.props.getSource("hello")}>Check</button>
I am passing hello
to the following action...
export const getSource = (string) => {
return {
type: "SOURCE_RECEIVED",
payload: string
}
}
I also have an action listener in my app that listens for this action...
export default function (state=null, action) {
switch(action.type) {
case "SOURCE_RECEIVED":
return action.payload;
break;
}
return state;
}
I am also combining the action listener...
import String from './reducer-listener';
const allReducers = combineReducers({
source: String
});
To create the store I am using the following code...
import allReducers from './reducers';
const store = createStore(allReducers);
const app = document.getElementById('app');
ReactDOM.render(
<Provider store={store}>
<Layout/>
</Provider>
, app);
My issue is, I want to save the string hello
in the app's current state so that it can be retrieved or updated later. Right now all I am doing is taking the string and printing it out to the console. I do not know what the proper way to store a state's value using redux.
How can I update my code so that I can save the hello
string in a location where it can be retrieved later?
Upvotes: 1
Views: 731
Reputation: 4141
Create a reducer like below
var userReducer = function (state = {}, action) {
switch (action.type) {
case 'SET_NAME':
return {
...state,
name: action.name
}
default:
return state;
}
}
You can create the store using the below code
import { createStore } from 'redux'
let store = createStore(userReducer)
at this moment you can test the state by
console.log('store state after initialization:', store.getState())
Create action creator like this
var setNameActionCreator = function (name) {
return {
type: 'SET_NAME',
name: name
}
}
You can store any value to the store by dispatching the action creator like below
store.dispatch(setNameActionCreator('bob'))
Dispatch function is provided by Redux and will propagate our action and it can be called in your button click
You will get the updated state by
console.log('store state after action SET_NAME:', store.getState())
Upvotes: 0
Reputation: 79248
Check out the docs on mapStateToProps
here:
Essentially you want to "connect" your component to the redux store like this:
import { connect } from 'react-redux'
const mapStateToProps = (state, ownProps) => {
return {
source: state.source
}
}
const TheConnectedComponent = connect(
mapStateToProps
)(TheComponent);
Upvotes: 1