Reputation: 516
I am fairly new to react native, the issue I'm having is trying to get data from an action in componentdidmount but when I set my props the data is null. The props are being set if I access them in the render method. Can someone please look at the code and tell me what I am doing wrong.
Below is where I'm getting the action
export const Accountability = connect(
// inject states
(state: States) => ({
// props.loading -> modules.app.loading
loading: state.app.loading,
doctorName: state.doctor.doctorName
}),
// inject actions
dispatch => ({
doDoctors: () =>
dispatch(actions.doctor.getDoctors())
})
)(AccountabilityView)
This is where I'm calling it.
render() {
const {loading, doDoctors, doctorName } = this.props
// Getting the data here.
doDoctors()
}
One thing I notice is that I am getting a warning in the console
ExceptionsManager.js:82 Warning: Cannot update during an existing state transition (such as within render
). Render methods should be a pure function of props and state.
UPDATE: I currently have all my files separate(action, reducer, constants, index). My action gets data from an API call. Below is my reducer:
import { handleActions } from 'redux-actions'
import { LOAD_DOCTORS } from './constants'
export type DoctorState = {
doctorName: string
}
const initialState: DoctorState = {
doctorName: '',
}
export default handleActions(
{
[LOAD_DOCTORS]: (state: DoctorState = initialState, action): DoctorState
=> {
const p = action.payload
return {
doctorName: p.doctorName,
}
},
},
initialState
)
UPDATE:2 This is what the code shows in the console, note doDoctors which returns an array is empty on the first call. When called in ComponentDidMount it only shows the first and not the second.
ComponentDidMount
{screenProps: undefined, navigation: {…}, loading: true, doctorName: "",
doDoctors: ƒ}
render
{screenProps: undefined, navigation: {…}, loading: true, doctorName: "",
doDoctors: ƒ}
{screenProps: undefined, navigation: {…}, loading: true,
doctorName: Array(10), doDoctors: ƒ}
Any help would be appreciated.
Upvotes: 1
Views: 1491
Reputation: 6742
Possible events where you could call your action
are => componentDidMount
and componentWillReceiveProps
... render
method is only used for returning some jsx
based on the update of your component props
:
class YourComponent extends React.Component {
componentDidMount() {
// Here's where you call your action,
// first time your component is loaded: <<<===
this.props.doDoctors();
}
componentWillReceiveProps(nextProps) {
// Here's where you could call your action,
// if the component is already mounted: <<<===
this.props.doDoctors();
}
render() {
const {loading, doctorName } = this.props;
return (
<View>
...
</View>
);
}
}
Upvotes: 0