1

I'm using reactjs in front end and nodejs as backend. I'm calling my backend (localhost:3001/api/tunes) through this code :

componentDidMount(){
    fetch("/api/itunes")
    .then((results)=>{
        this.setState({queryResult:results});
    })
}

This code is supposed to return a single string value which I'm assigning to local state variable queryResult. I can't understand why the code gives error - objects are not valid react child.

My render function :

render(){
            return(
                <div>
                    <form class="form-inline my-2 my-lg-0">
                        <input class="form-control mr-sm-2" type="search" placeholder="Search" 
                        value={this.state.queryValue} onChange={this.handleQueryChange} />
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit"
                        onClick={this.submitQuery}></button>
                    </form>

                    <div>{this.state.queryResult}</div>
                </div>

        );
}

this is what I'm getting from my server:

router.get('/api/itunes',(req,res,next)=>{
    request('https://itunes.apple.com/search?term=jack+johnson', 
function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body) // Print the google web page.
        var result =JSON.parse(body);
        res.send(result.results[0].artistName);
        }
    });
});
9
  • 1
    please show the render method Commented Dec 16, 2017 at 18:04
  • You can't just render the response from the API. You'll have to map it to individual elements. Commented Dec 16, 2017 at 18:06
  • You are trying to render <div>{this.state.queryResult}</div> and hence you get this error, you need to map over your response and render it Commented Dec 16, 2017 at 18:08
  • even though the result is string, then also i can't just assign to local state variable ? Commented Dec 16, 2017 at 18:08
  • 1
    @ASHUTOSHCHANDRA It's not a string, judging by the error message. Commented Dec 16, 2017 at 18:08

1 Answer 1

0

You are trying to render whole object which is this.state.queryResult .

React cannot render objects.You must convert this to String or have to extract each value from the object.

You can easily check this using {console.log(this.state.queryResult)}

Sign up to request clarification or add additional context in comments.

2 Comments

can you suggest how to do it properly, returned value from the api is a string.
{JSON.stringify(this.state.queryResult)} But it is not the appropriate method you have to extract each attribute from the object and print

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.