1

I'm trying to make a fetch request to my server and set the response json as the component's state. I get this error

Objects are not valid as a React child (found: object with keys {description, 
    id, matched_substrings, place_id, reference, structured_formatting, terms, types}). If you meant to render a collection of children, use an array instead.
    in li (at Search.js:25)
    in ul (at Search.js:30)
    in div (at Search.js:28)
    in Search (at index.js:8)

this is my code -

import React from 'react'
import { ReactDOM } from "react-dom";

export default class Search extends React.Component {
constructor(props) {
    super(props);
    this.state = { 
        places: []
     }
     this.handleUserInput = this.handleUserInput.bind(this)
}
handleUserInput(e) {
    var searchInput = e.target.value;
    var url = '/searchLocation/autocomplete?text=' + (searchInput)

    if (searchInput.length > 2) {
        fetch(url).then(function(response) {return response.json()})
        .then((responseJson) => this.setState({places: responseJson["predictions"]}));    
        //.then( responseJson => console.log(responseJson["predictions"]))
    }
}
render() {
    const placeList = this.state.places.map(place => 
        {
            return <li>{place}</li>
        });
    return (
        <div>
            <input onChange={this.handleUserInput} type="text" id="PlaceSearch" />
            <ul>
                { placeList }
            </ul>    
        </div>  
    );      
}
}

I found similiar errors by googling it but none helped..

Thank you very much for helping

1
  • btw, in your example, you are recreating the placeList function everytime render is called, which is not great for performances. You should make it a method of the class instead Commented Jul 21, 2018 at 21:05

2 Answers 2

3

This issue is you are trying to render place which I assume is an object inside the li.

you need to choose which property to render

ex:

return <li>{place.id}</li>
Sign up to request clarification or add additional context in comments.

Comments

0

I think you're missing parenthesis;

 const placeList = this.state.places.map(place => 
    {
        return ( <li>{place}</li> )
    });

1 Comment

Thats not the problem.. the error is in line 18 where I set the state..

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.