Reputation: 81
Hi I have a question about page render I have a Data define in state and its structure like below
this.state = {
Data: this.props.navigation.getParam('Data', 'error')
};
[{Name: 'Jason',
Tel: '000000'},
{Name: 'Lily',
Tel: '001255'},
{Name: 'Henry',
Tel: '088000'},
]
I call API to add items for each object and I want to let the Data like below
[{Name: 'Jason',
Tel: '000000',
Addr: 'dfsfsdgdrtesf'},
{Name: 'Lily',
Tel: '001255',
Addr: 'rgrhrerger'},
{Name: 'Henry',
Tel: '088000',
Addr: 'dfsfsdgdrrgrgtesf'},
]
I do this in the ''' async componentDidMount() {
for (i = 0; i < Object.keys(this.state.Data).length; i++) {
await Call_Some_API() => {
this.state.Data[i].Addr = (Object.keys(jsonData.Other).length + 1).toString();
this.setState(this.state.Data);
});
}
console.log(this.state.Data)
} ''' console.log(this.state.Data) is correct! but I can not get the Addr in my component even if I call this.setState(this.state.Data).
I want to show the Addr but it always empty It like read old Data not the new one or maybe my method is not right. Give me a help! thank you
Upvotes: 1
Views: 206
Reputation: 4540
I can not get the Addr in my component
Because you are mutating state with this line:
this.state.Data[i].Addr = (Object.keys(jsonData.Other).length + 1).toString();
Something like this should work:
for (i = 0; i < Object.keys(this.state.Data).length; i++) {
await Call_Some_API() => {
const addr = (Object.keys(jsonData.Other).length + 1).toString();
let tempState = [...this.state.Data];
tempState[i] = {...tempState[i], "Addr": addr};
this.setState({ Data: tempState });
});
}
Upvotes: 1
Reputation: 3112
See if this works.
componentDidMount(){
Call_API.then(
res => {
this.setState( prevState => {
res.data.map( addr => {
prevState.map( item => {
item['Addr'] = addr
})
})
})
}
)
}
Upvotes: 0
Reputation: 6280
You should not change the state directly, instead you should use setState
function to do that.
Upvotes: 0
Reputation: 1096
You should use this.setState({ Data: this.state.Data });
.
There is more info in the setState
documentation on the react docs.
Also you probably should clone the state before changing it as mentioned on the react docs:
Never mutate
this.state
directly, as callingsetState()
afterwards may replace the mutation you made. Treatthis.state
as if it were immutable.
Upvotes: 0