Search code examples
reactjssuperagent

Trouble referencing API (React and Superagent)


So by using postman I've managed to call the url for yummly. I'd like to render my search results. Currently in the render from lines 29 - 36 I have a fake search just to make sure the Dom works, and it does. How do I get the api search from lines 52 - 60 to show in 29 - 36.

import React from 'react';
import Request from 'superagent';
import _ from 'lodash';


export class Yum extends React.Component {
    constructor(){
        super();
        this.state = {};
    }

    componentWillMount(){

        /*var url = "http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q"
        Request.get(url).then((response) => {
            console.log(response.body);
            this.setState({
                recipes: response.body.matches,
                total: response.body.totalResults           
            });
        });*/
        this.search();
    }

    updateSearch(){
        this.search(this.refs.query.value);
    }

    render(){
        

        const title = 'Onion Soup';
        const ingredients = ["onions", "beef stock"];
        const listItems = ingredients.map((ingredient) => {
          return (<h5>{ingredient}</h5>);
        });
        
        
        return(
            
            <div>
                <input ref="query" onChange = { (e) => {this.updateSearch();} } type="text" />
                
                <h4>{title}</h4>
                <ul>
                <li>{listItems}</li>
                </ul>
            </div>
        )
    }

    search(query = "onion") {
        var url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q${query}&maxResult=1`
        Request.get(url).then((response) => {
            console.log(response.body.matches[0]);
            console.log(query);
            this.setState({
                recipes: response.body.matches[0],
                //total: response.body.totalResults
            });
        });
    }
}

export default Yum;


Solution

  • Here you go I have cleaned up your code a bit, please give it a try

    import React from 'react';
    import Request from 'superagent';
    import _ from 'lodash';
    
    export class Yum extends React.Component {
        constructor(){
            super();
            this.state = {
                searchQuery: 'onion'
                recipe: {
                    ingredients: []
                }
            };
    
            this.search = this.search.bind(this);
            this.queryUpdate = this.queryUpdate.bind(this);
        }
    
        componentWillMount(){
            this.search(this.state.searchQuery);
        }
    
        render(){
            const title = 'Onion Soup'; // Get this from somwhere else ?
            const {recipe, searchQuery} = this.state; // Get state properties
    
            const listItems = _.get(recipe, 'ingredients', []).map((ingredient) => {
                return (<h5>{ingredient}</h5>);
            });
    
            return(
                <div>
                    <input onChange={this.queryUpdate} type="text" value={searchQuery} />
    
                    <h4>{title}</h4>
                    <ul>
                        <li>{listItems}</li>
                    </ul>
                </div>
            )
        }
    
        queryUpdate(e) {
            const searchQuery = event.target.value; // Get new value from DOM event
            this.setState({searchQuery}); // Save to state
            this.search(searchQuery); // Search
        }
    
        search(searchQuery) {
            const url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&q=${searchQuery}&maxResult=1`
            Request.get(url).then((response) => {
                this.setState({
                    recipe: response.body.matches[0]
                });
            });
        }
    }
    
    export default Yum;
    

    Here are some of the issues I noticed:

    • Typo in URL: =q instead of q=
    • You should save the state of the text input in a state variable instead of using refs
    • smaller details commented in code