Reputation: 137
How can I wait for react-redux to return my new connected component? Basically, I have an index screen where I make a query to a database to save the clients, the response of that api call is the argument with which I want to trigger my SAVE_CUSTOMERS action and then make a map in the view.
This error is because the object as such that I want to make the map does not yet exist, and this is why I forge a wait for that Hash and if it works.
I have several ways to force this to work, but I'm here for a fancy solution 😂
customers.js
import React from "react";
import bridge from "../../helpers/bridge/index";
import { save_customers } from "../../../actions/customers";
import CustomersUI from "../../components/Customers/CustomersUI";
import { connect } from "react-redux";
class CustomersScreen extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
bridge
.getCustomers(this.props.user.access_token)
.then((customers) => this.props.save_customers(customers))
.catch((error) => console.error(error));
}
render() {
return (
<CustomersUI
customers={this.props.customers}
/>
);
}
}
export default connect(
(state) => ({
user: state.user,
customers: state.customers,
}),
{
save_customers: save_customers,
}
)(CustomersScreen);
My reducer
export default (state = {}, action) => {
switch (action.type) {
case "SAVE_CUSTOMERS":
return action.customers;
default:
return state;
}
};
And... The action,
export function save_customers(customers) {
return {
type: "SAVE_CUSTOMERS",
customers,
};
}
Obviously I have a combineReducers exporting everything.
Perhaps waiting for the component to be connected is not exactly the most fancy way to solve it, it is just the closest idea I have about it. Less than 1 week ago I am in React Native, never used Redux before. Thank you!
Upvotes: 0
Views: 48
Reputation: 42526
The customers
array from your state might be undefined while it is waiting for the response from getCustomers
. Therefore, on your render method, you should conditionally render the child CustomersUI
only when customers
is defined.
render() {
const { customers } = this.props;
return (
customers && (
<CustomersUI
customers={this.props.customers}
/>
)
);
}
Alternatively, the CustomersUI
component should handle undefined values, such that it won't throw that error.
Upvotes: 1