codemarvel
codemarvel

Reputation: 57

react setState function is not workin

I am new at react and I have been trying to apply event handling in react but facing some Problem on onclick event. When the button "show me of germany" is called the Page then stuck to loading only ...

Here is the code i have written ..

class App extends Component {
    constructor(props) {
        super(props);

        this.state = { articles: [],
                isLoaded:false ,
                country:'us'
                }
       
        this.change = this.change.bind(this);
    }


    componentDidMount() {
        const APIurl = `https://newsapi.org/v2/top-headlines?country=${this.state.country}&apiKey=${API_KEY}`;
        fetch(APIurl)
            .then(response => response.json())
            .then(json => {
                this.setState({
                    articles: json.articles,
                    isLoaded:true
                })
            })
    }
   // function to change the state
    change()
    {
        this.setState({
            articles: [],
            isLoaded:false ,
            country:"de"

        })
    }   
   
    render() {
      const { isLoaded,articles } = this.state;
      if(!isLoaded)
      {
          return (<h1>Loading....</h1>)
      }
     
        return (
            <div>
                <Navbar/>
                <button onClick={this.change}>show me of germany</button>
                <ul>
                    {articles.map(item=>(
                           <News item={item}/>
                    ))}
                </ul>
            </div>
       );
   }
}
export default App;

Hope you understood the problem

Upvotes: 0

Views: 46

Answers (1)

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1565

You have to do request again.

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      articles: [],
      isLoaded: false,
      country:'us'
    }
       
    this.change = this.change.bind(this);
  }


  componentDidMount() {
    fetchData(this.state.country);
  }

  componentDidUpdate(prevProps, prevState) {
    const { country: prevCountry } = prevState;
    const { country: nextCountry } = this.state;

    if (prevCountry !== nextCountry) {
      fetchData(nextCountry);
    }
  }

  change() {
    this.setState({ country: 'de' });
  }

  fetchData(country) {
    this.setState({ articles: [], isLoaded: false });

    fetch(
      `https://newsapi.org/v2/top-headlines?country=${country}&apiKey=${API_KEY}`
    )
      .then(res => res.json())
      .then(({ articles }) => {
        this.setState({ articles, isLoaded: true });
      })
      .catch(console.error);
  }
   
  render() {
    //...
  }
}

export default App;

Upvotes: 1

Related Questions