Reputation: 21
I'm working on a project for school and I get this error for a non-render portion of my code.
fetchCharacterData = () => {
var encodedURI = window.encodeURI(this.props.uri);
return axios.get(encodedURI).then(response => {
this.setState(() => {
return {
characterData: response.data
};
});
});
};
It has a problem with the line that reads this.setState(() => { I tried the suggestions on the other questions and nothing seems to work with this line of code.
componentDidMount() {
this.fetchCharacterData();
console.log("MOUNT");
}
render() {
console.log(this.state.characterData);
if (this.state.characterData.length === 0) {
return <div>Failed to fetch data from server</div>;
}
const characters = this.state.characterData.map(character => {
return <div key={character.name}><em>: {character.name}</em>: {character.class} </div>
});
}
Upvotes: 1
Views: 66
Reputation: 546
try adjust your render function like this.
render() {
if (this.state.characterData.length === 0) {
return <div>Failed to fetch data from server</div>;
}
const characters = this.state.characterData.map(character => {
return <div key={character.name}><em>: {character.name}</em>: {character.class} </div>
});
/******************/
return characters;
/******************/
}
Upvotes: 2
Reputation: 1191
You need to return something in your render function - the error is unrelated to the code you pasted.
class YourComponent extends React.Component {
// ...
fetchCharacterData = () => {
var encodedURI = window.encodeURI(this.props.uri);
return axios.get(encodedURI).then(response => {
this.setState(() => {
return {
characterData: response.data
};
});
});
};
// ...
// It's this part causing the error.
// It either returns nothing, or doesn't exist.
render() {
return <div>Your page content</div> // or return null
}
}
Upvotes: 2