How to setState to answer from APi and use map

筅森魡賤 提交于 2019-12-25 00:08:49

问题


Im trying to create recipes searcher. In App.js I receive query from search input from another component and I want to setState to answer from APi. Console.log from callback in setState shows updated state but the state is not updated. I need setState updaed so I can use map on it and display list of recipes in render. It gives me error map is not a function because this.state.recipesList is still empty. Anyone can help me ?

class App extends Component {
  state = {
    query: "",
    recipesList: []
  };

  getQuery = query => {
    const key = "2889f0d3f51281eea62fa6726e16991e";
    const URL = `https://www.food2fork.com/api/search?key=${key}&q=${query}`;

    fetch(URL)
      .then(res => res.json())
      .then(res => {
        this.setState(
          {
            recipesList: res
          },
          () => {
            console.log(this.state.recipesList);
          }
        );
      });
    console.log(this.state.recipesList);
  };
  render() {
     const test = this.state.recipesList.map(item => {
       return (
         <div className="recispesList">
           <h1>{item.title}</h1>
        </div>
       );
     });

    return (
      <div className="App">
        <Search query={this.getQuery} />
        <div className="contentWrapper">{}</div>
      </div>
    );
  }
}

Search component:

class Search extends Component {
  state = {
    searchValue: ""
  };

  handleChange = val => {
    let searchValue = val.target.value;
    this.setState({
      searchValue
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.setState({
      searchValue: ""
    });
    this.props.query(this.state.searchValue);
  };
  render() {
    return (
      <div className="searchWrapper">
        <form onSubmit={this.handleSubmit}>
          <input onChange={this.handleChange} value={this.state.searchValue} />
          <button />
        </form>
      </div>
    );
  }
}

export default Search;

回答1:


It seems that instead of directly assigning the whole response to recipesList:

this.setState(
  {
    recipesList: res
  },
  () => {
    console.log(this.state.recipesList);
  }
);

you need to get recipes array first via res.recipes:

this.setState(
  {
    recipesList: res.recipes
  },
  () => {
    console.log(this.state.recipesList);
  }
);


来源:https://stackoverflow.com/questions/56368443/how-to-setstate-to-answer-from-api-and-use-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!