Reputation: 767
thanks in advance for taking a look my questions. So I am POSTing to a DB from the CreateItem component via the submitItem function, then when the promise is returned, I call a pullAllItems to GET all rows for the categories table of my DB to update the state of categories:
React Component:
import React, { Component } from 'react';
import CreateItem from './components/CreateItem';
import Categories from './components/Categories';
// stylesheets
import './stylesheets/App.css';
class App extends Component {
constructor() {
super();
this.state = {
categories: [],
tasks: []
};
this.submitItem = this.submitItem.bind(this);
this.pullAllItems = this.pullAllItems.bind(this);
}
componentWillMount() {
fetch('/api/categories')
.then(res => res.json())
.then(res => {
this.setState({
categories: res
});
});
}
submitItem(title) {
const category = {
title
}
fetch('/api/categories', {
method: 'POST',
body: JSON.stringify(category),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(this.pullAllItems('categories'));
}
pullAllItems(type) {
const key = type;
let obj = {};
fetch('/api/' + type)
.then(res => res.json())
.then(res => {
obj[key] = res;
this.setState({
obj
}, () => {
console.log(this.state.categories);
});
});
}
render() {
return (
<div className="App">
<CreateItem submitItem={this.submitItem} />
<Categories categories={this.state.categories} pullAllTasks={this.pullAllItems}/>
</div>
);
}
}
If I console log the response, I get the additional row that was POSTed with the submitItem function; however, when I update the state of categories in my pullAllItems function, the state does not update (even in the callback function of setState). I am new to react, and have looked everywhere I can to see what I am missing, but can't get a clear-cut answer anywhere. Any help is greatly appreciated!
Upvotes: 1
Views: 132
Reputation: 2145
I think you would want to do this.setState(obj)
so that they dynamic key gets merged in to the state.
Upvotes: 1