Reputation: 271
This problem was basically solved here but It's a little bit outdated.
I was trying to set state after fetch is done. Unfortunately the basic solution putting fetch in ComponentDidMount()
is not working as I wanted (it shows that state is undefined) so I've found around solution like this: declaring global variable, assing fetched data to this global variable and then in then()
do this.setState()
. It's working but I have a feeling this is not a completely correct solution.
Is there a better/cleaner way to do setState inside fetch?
Here's fragment of my code:
var fetchedData = null;
class Main extends Component {
state = {
data: "",
};
componentDidMount() {
fetch("some-url", {
credentials: "include",
}).then((res) => {
res.json()
.then((data) => {
fetchedData = data;
})
.then(() => {
if (fetchedData.someData) {
this.setState({ data: fetchedData.someData });
}
});
});
}
//rest of code
}
Upvotes: 0
Views: 56
Reputation: 377
class Main extends Component {
constructor(props) {
super(props);
this.state = {
data: ''
}
}
componentDidMount() {
fetch("some-url", {
credentials: "include",
}).then((res) => res.json())
.then(data => this.setState({data}));
}
//rest of code
}
Upvotes: 0
Reputation:
Try this
class Main extends Component {
state = {
data: "",
};
async componentDidMount() {
let res = await fetch("some-url", {credentials: "include"});
let data = await res.json();
if (data.someData) {
this.setState({ data: data.someData });
}
});
}
//rest of code
}
Upvotes: 1