1
votes

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>
    });
}
2
Can you paste the contents of your render function? That's where this error would be caused. - Ross Allen
Added it above. - The Lilian
You are creating that characters array, but you are indeed not returning anything from the render method on that path. - Bergi
According to my console, it's pulling the information that is supposed to be displayed. I'm not sure what to change as this is code given by the school that they claim to work. - The Lilian
You don’t return the results of the map. - Dave Newton

2 Answers

2
votes

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
    }
}
2
votes

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;
    /******************/
}