Bolboa Bolboa - 18 days ago 8
React JSX Question

Redux proper location/method to store state value

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?

Answer

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);
Comments