Reputation: 790
I am wondering if someone can help me out with this since I am new to react-native and redux.
I want to populate a FlatList with just a name and I am using this classes (along with others obviously):
actions.js
const LOAD_CLIENT = 'LOAD_CLIENT';
export async function loadClient() {
const client = await Parse.Query("Client");
return {
type: LOAD_CLIENT,
client: client,
};
}
reducers.js
import { LOAD_CLIENT } from '../actions'
const initialState = {
objectId: null,
name: null,
};
function client(state: State = initialState, action: Action): State {
if (action.type === LOAD_CLIENT) {
let {objectId, name} = action.client; // de-structuring action data
return {
objectId,
name,
};
}
return state;
}
module.exports = client;
listScreen.js
import {
loadClient
} from './actions'
class SettingsScreen extends Component {
render() {
return (
<View style={styles.container}>
<FlatList style={styles.listStyle}
data={this.props.client}
renderItem={({item}) => <Text>{item.name}</Text>}
/>
</View>
)
}
}
export default SettingsScreen
What do I need to be able to populate the list with client.name? I followed Redux basics to get here but now I am stuck.
Upvotes: 0
Views: 460
Reputation: 191
Please change something like this in your file.
reducer.js
import { LOAD_CLIENT } from '../actions'
const initialState = {
data: null,
};
function client(state: State = initialState, action: Action): State {
if (action.type === LOAD_CLIENT) {
return Object.assign({}, state, {
data: action.client
});
}
return state;
}
module.exports = client;
listScreen.js
import { loadClient } from './actions'
import { connect } from 'react-redux';
class SettingsScreen extends Component {
constructor(props){
super(props);
this.state={
client: null,
}
}
componentDidMount(){
this.props.loadClientData();
}
componentWillReceiveProps(nextProps) {
if (nextProps.data != null) {
this.setState({
client: nextProps.data
});
}
}
render() {
return (
<View style={styles.container}>
<FlatList style={styles.listStyle}
data={this.state.client}
renderItem={({item}) => <Text>{item.name}</Text>}
/>
</View>
)
}
}
const mapStateToProps = (state) => ({
data: state.reducers.data
});
const mapDispatchToProps = (dispatch) => ({
loadClientData: () => dispatch(loadClient())
})
export default connect(mapStateToProps, mapDispatchToProps)(SettingsScreen)
or you can refer to this link for your practice.
https://medium.com/@imranhishaam/advanced-redux-with-react-native-b6e95a686234
Upvotes: 1
Reputation: 101
You are forgetting to connect your component.
import {connect} from 'react-redux;
{...}
const mapStateToProps = ({reducerName})=>{
const {name, objectId} = reducerName;
return {name, objectId}
}
after this name and objectId will be available on component props. But remember that the flatList data needs an array so your reducer should have a variable clients:[] that will populate on fetch with all the data. Flatlist wont work if u pass only an object, you need to pass an array of objects
Upvotes: 0